From 1d28c51c5c2422636509f33b9b56b89946a3fa95 Mon Sep 17 00:00:00 2001 From: Dmitry Zakharov Date: Fri, 24 Nov 2023 00:30:21 +0400 Subject: [PATCH] Rename to rescript-schema --- .vscode/settings.json | 2 +- CHANGELOG_NEXT.md | 18 +- CONTRIBUTING.md | 6 +- IDEAS.md | 1 + README.md | 16 +- bsconfig.json | 2 +- docs/integration-guide.md | 4 +- docs/js-usage.md | 216 ++-- docs/rescript-usage.md | 402 +++---- package.json | 14 +- packages/ppx/src/ppx/codecs.ml | 40 +- packages/ppx/src/ppx/codecs.mli | 2 +- packages/ppx/src/ppx/polyvariants.ml | 2 +- packages/ppx/src/ppx/polyvariants.mli | 2 +- packages/ppx/src/ppx/ppx_struct.ml | 4 +- packages/ppx/src/ppx/records.ml | 16 +- packages/ppx/src/ppx/records.mli | 2 +- packages/ppx/src/ppx/signature.ml | 10 +- packages/ppx/src/ppx/structure.ml | 24 +- packages/ppx/src/ppx/utils.ml | 4 +- packages/ppx/src/ppx/variants.ml | 2 +- packages/ppx/src/ppx/variants.mli | 2 +- packages/ppx/src/ppx_struct.opam | 12 +- packages/prepack/src/Prepack.bs.mjs | 113 +- packages/prepack/src/Prepack.res | 4 +- packages/tests/bsconfig.json | 4 +- packages/tests/src/benchmark/Benchmark.bs.mjs | 86 +- packages/tests/src/benchmark/Benchmark.res | 44 +- packages/tests/src/benchmark/comparison.js | 16 +- packages/tests/src/core/Example_test.res | 10 +- .../tests/src/core/S_Array_length_test.res | 28 +- packages/tests/src/core/S_Array_max_test.res | 28 +- packages/tests/src/core/S_Array_min_test.res | 28 +- .../tests/src/core/S_Error_message_test.res | 2 +- .../tests/src/core/S_Error_raise_test.res | 2 +- packages/tests/src/core/S_Float_max_test.res | 32 +- packages/tests/src/core/S_Float_min_test.res | 28 +- packages/tests/src/core/S_Int_max_test.res | 28 +- packages/tests/src/core/S_Int_min_test.res | 28 +- packages/tests/src/core/S_Int_port_test.res | 24 +- packages/tests/src/core/S_JsApi_test.ts | 438 +++---- .../src/core/S_Object_unknownKeys_test.res | 22 +- .../tests/src/core/S_Option_default_test.res | 18 +- .../src/core/S_Option_getOrWith_test.res | 44 +- .../tests/src/core/S_Option_getOr_test.res | 52 +- .../tests/src/core/S_String_cuid_test.res | 24 +- .../tests/src/core/S_String_datetime_test.res | 32 +- .../tests/src/core/S_String_email_test.res | 24 +- .../tests/src/core/S_String_length_test.res | 28 +- packages/tests/src/core/S_String_max_test.res | 28 +- packages/tests/src/core/S_String_min_test.res | 28 +- .../tests/src/core/S_String_pattern_test.res | 36 +- .../tests/src/core/S_String_trim_test.res | 8 +- packages/tests/src/core/S_String_url_test.res | 20 +- .../tests/src/core/S_String_uuid_test.res | 20 +- packages/tests/src/core/S_array_test.res | 46 +- packages/tests/src/core/S_bool_test.res | 30 +- packages/tests/src/core/S_catch_test.res | 64 +- packages/tests/src/core/S_custom_test.res | 38 +- packages/tests/src/core/S_deprecate_test.res | 34 +- .../tests/src/core/S_description_test.res | 16 +- packages/tests/src/core/S_dict_test.res | 50 +- .../tests/src/core/S_failWithError_test.res | 8 +- packages/tests/src/core/S_float_test.res | 32 +- packages/tests/src/core/S_inline_test.res | 430 +++---- packages/tests/src/core/S_int_test.res | 44 +- .../tests/src/core/S_isAsyncParse_test.res | 24 +- packages/tests/src/core/S_jsonString_test.res | 24 +- packages/tests/src/core/S_json_test.res | 68 +- packages/tests/src/core/S_list_test.res | 22 +- .../tests/src/core/S_literal_Array_test.res | 32 +- .../tests/src/core/S_literal_Boolean_test.res | 28 +- .../tests/src/core/S_literal_NaN_test.res | 24 +- .../tests/src/core/S_literal_Null_test.res | 24 +- .../tests/src/core/S_literal_Number_test.res | 32 +- .../tests/src/core/S_literal_Object_test.res | 36 +- .../tests/src/core/S_literal_String_test.res | 28 +- .../src/core/S_literal_Undefined_test.res | 24 +- packages/tests/src/core/S_name_test.res | 32 +- packages/tests/src/core/S_never_test.res | 26 +- packages/tests/src/core/S_null_test.res | 70 +- .../src/core/S_object_discriminant_test.res | 110 +- .../tests/src/core/S_object_escaping_test.res | 60 +- .../tests/src/core/S_object_spread_test.res | 6 +- packages/tests/src/core/S_object_test.res | 284 ++--- .../S_object_withoutDeclaredFields_test.res | 30 +- packages/tests/src/core/S_option_test.res | 56 +- .../core/S_parseAnyAsyncInStepsWith_test.res | 204 ++-- .../src/core/S_parseAnyOrRaiseWith_test.res | 14 +- .../src/core/S_parseJsonStringWith_test.res | 18 +- packages/tests/src/core/S_parseWith_test.res | 14 +- packages/tests/src/core/S_preprocess_test.res | 100 +- packages/tests/src/core/S_recursive_test.res | 90 +- packages/tests/src/core/S_refine_test.res | 20 +- .../src/core/S_serializeOrRaiseWith_test.res | 8 +- .../core/S_serializeToJsonStringWith_test.res | 20 +- .../tests/src/core/S_serializeWith_test.res | 62 +- packages/tests/src/core/S_string_test.res | 22 +- packages/tests/src/core/S_transform_test.res | 118 +- packages/tests/src/core/S_tuple1_test.res | 18 +- packages/tests/src/core/S_tuple2_test.res | 18 +- packages/tests/src/core/S_tuple_test.res | 110 +- packages/tests/src/core/S_union_test.res | 74 +- packages/tests/src/core/S_unknown_test.res | 26 +- packages/tests/src/core/S_variant_test.res | 74 +- packages/tests/src/genType/GenType.bs.mjs | 8 +- packages/tests/src/genType/GenType.gen.ts | 8 +- packages/tests/src/genType/GenType.res | 2 +- .../tests/src/genType/GenType_test_type.ts | 2 +- .../tests/src/ppx/Ppx_Example_test.bs.mjs | 50 +- packages/tests/src/ppx/Ppx_Example_test.res | 12 +- .../tests/src/ppx/Ppx_General_test.bs.mjs | 42 +- packages/tests/src/ppx/Ppx_General_test.res | 26 +- packages/tests/src/ppx/Ppx_General_test.resi | 6 +- .../src/ppx/Ppx_Polyvariants_test.bs.mjs | 40 +- .../tests/src/ppx/Ppx_Polyvariants_test.res | 14 +- .../tests/src/ppx/Ppx_Primitives_test.bs.mjs | 214 ++-- .../tests/src/ppx/Ppx_Primitives_test.res | 132 +-- .../tests/src/ppx/Ppx_Records_test.bs.mjs | 60 +- packages/tests/src/ppx/Ppx_Records_test.res | 32 +- .../tests/src/ppx/Ppx_Variants_test.bs.mjs | 40 +- packages/tests/src/ppx/Ppx_Variants_test.res | 20 +- packages/tests/src/utils/U.bs.mjs | 56 +- packages/tests/src/utils/U.res | 46 +- pnpm-lock.yaml | 4 +- src/S.bs.mjs | 128 +- src/S.d.ts | 244 ++-- src/S.resi | 10 +- src/S_Core.bs.mjs | 984 ++++++++-------- src/S_Core.res | 1042 ++++++++--------- src/S_Core.resi | 10 +- 131 files changed, 4100 insertions(+), 4104 deletions(-) diff --git a/.vscode/settings.json b/.vscode/settings.json index dbc8bbcc..0a48960c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -1,6 +1,6 @@ { "ocaml.sandbox": { "kind": "opam", - "switch": "struct" + "switch": "rescript-schema" } } diff --git a/CHANGELOG_NEXT.md b/CHANGELOG_NEXT.md index c6441b1a..215fd200 100644 --- a/CHANGELOG_NEXT.md +++ b/CHANGELOG_NEXT.md @@ -8,44 +8,44 @@ In progress ### How to use -Add `@struct` in front of a type defenition. +Add `@schema` in front of a type defenition. ```rescript -@struct +@schema type rating = | @as("G") GeneralAudiences | @as("PG") ParentalGuidanceSuggested | @as("PG13") ParentalStronglyCautioned | @as("R") Restricted -@struct +@schema type film = { @as("Id") id: float, @as("Title") title: string, @as("Tags") - tags: @struct(S.array(S.string)->S.default(() => [])) array, + tags: @schema(S.array(S.string)->S.default(() => [])) array, @as("Rating") rating: rating, @as("Age") - deprecatedAgeRestriction: @struct(S.int->S.option->S.deprecate("Use rating instead")) option, + deprecatedAgeRestriction: @schema(S.int->S.option->S.deprecate("Use rating instead")) option, } ``` -This will automatically create `filmStruct` of type `S.t`: +This will automatically create `filmSchema` of type `S.t`: ```rescript -let ratingStruct = S.union([ +let ratingSchema = S.union([ S.literal(GeneralAudiences), S.literal(ParentalGuidanceSuggested), S.literal(ParentalStronglyCautioned), S.literal(Restricted), ]) -let filmStruct = S.object(s => { +let filmSchema = S.object(s => { id: s.field("Id", S.float), title: s.field("Title", S.string), tags: s.field("Tags", S.array(S.string)->S.default(() => [])), - rating: s.field("Rating", ratingStruct), + rating: s.field("Rating", ratingSchema), deprecatedAgeRestriction: s.field("Age", S.int->S.option->S.deprecate("Use rating instead")), }) ``` diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index b9fe3fa7..68fd9b9b 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -11,7 +11,7 @@ Before you start working on a contribution, create an issue describing what you The following steps will get you setup to contribute changes to this repo: 1. Fork this repo. -2. Clone your forked repo: `git clone git@github.com:{your_username}/rescript-struct.git` +2. Clone your forked repo: `git clone git@github.com:{your_username}/rescript-schema.git` 3. Install [pnpm](https://pnpm.io/) if not available `npm i -g pnpm@7.11.0` 4. Run `pnpm i` to install dependencies. 5. Start playing with the code! @@ -25,7 +25,7 @@ Make sure running the below commands in `packages/ppx/src`. 1. Create a sandbox with opam ``` -opam switch create struct 4.12.1 +opam switch create rescript-schema 4.12.1 ``` 2. Install dependencies @@ -55,4 +55,4 @@ npm run test -- --watch ## License -By contributing your code to the rescript-struct GitHub repository, you agree to license your contribution under the MIT license. +By contributing your code to the rescript-schema GitHub repository, you agree to license your contribution under the MIT license. diff --git a/IDEAS.md b/IDEAS.md index 4740a954..aa40d59d 100644 --- a/IDEAS.md +++ b/IDEAS.md @@ -49,6 +49,7 @@ let trimContract: S.contract string> = S.contract(s => { - Make `error.reason` tree-shakeable - Update `Literal` `tagged` to include `text`, `value` and `kind`. So it's more convinient and smaller bundle-size - Turn `String.email` -> `email`, `String.min` -> `stringMin` for tree-shaking +- Rename `InvalidJsonStruct` error, since after `rescript-struct`->`rescript-schema` it became misleading ## v??? diff --git a/README.md b/README.md index a8811d69..6137a985 100644 --- a/README.md +++ b/README.md @@ -1,12 +1,12 @@ -[![CI](https://github.com/DZakh/rescript-struct/actions/workflows/ci.yml/badge.svg)](https://github.com/DZakh/rescript-struct/actions/workflows/ci.yml) -[![codecov](https://codecov.io/gh/DZakh/rescript-struct/branch/main/graph/badge.svg?token=40G6YKKD6J)](https://codecov.io/gh/DZakh/rescript-struct) -[![npm](https://img.shields.io/npm/dm/rescript-struct)](https://www.npmjs.com/package/rescript-struct) +[![CI](https://github.com/DZakh/rescript-schema/actions/workflows/ci.yml/badge.svg)](https://github.com/DZakh/rescript-schema/actions/workflows/ci.yml) +[![codecov](https://codecov.io/gh/DZakh/rescript-schema/branch/main/graph/badge.svg?token=40G6YKKD6J)](https://codecov.io/gh/DZakh/rescript-schema) +[![npm](https://img.shields.io/npm/dm/rescript-schema)](https://www.npmjs.com/package/rescript-schema) -# ReScript Struct +# ReScript Schema The fastest composable parser/serializer for ReScript (and TypeScript) -> ⚠️ Be aware that **rescript-struct** uses `eval`. It's usually fine but might not work in some environments like Cloudflare Workers or third-party scripts used on pages with the [script-src](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) header. +> ⚠️ Be aware that **rescript-schema** uses `eval`. It's usually fine but might not work in some environments like Cloudflare Workers or third-party scripts used on pages with the [script-src](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/script-src) header. Highlights: @@ -15,14 +15,14 @@ Highlights: - Works with any Js value, not only `Js.Json.t` - Support for asynchronous transformations - Immutable API with both result and exception-based operations -- Easy to create _recursive_ structs +- Easy to create _recursive_ schema - Detailed error messages -- Strict mode for object structs to prevent excessive fields and many more built-in helpers +- Opt-in strict mode for object schema to prevent excessive fields and many more built-in helpers - Works with plain JavaScript/TypeScript too! You don't need to use ReScript - The **fastest** composable validation library in the entire JavaScript ecosystem ([benchmark](https://moltar.github.io/typescript-runtime-type-benchmarks/)) - Small JS footprint & tree-shakable API ([Comparison with Zod and Valibot](./docs/js-usage.md#comparison)) -Also, it has declarative API allowing you to use **rescript-struct** as a building block for other tools, such as: +Also, it has declarative API allowing you to use **rescript-schema** as a building block for other tools, such as: - [rescript-envsafe](https://github.com/DZakh/rescript-envsafe) - Makes sure you don't accidentally deploy apps with missing or invalid environment variables - [rescript-json-schema](https://github.com/DZakh/rescript-json-schema) - Typesafe JSON schema for ReScript diff --git a/bsconfig.json b/bsconfig.json index 8b02ce5b..02b5ad82 100644 --- a/bsconfig.json +++ b/bsconfig.json @@ -1,5 +1,5 @@ { - "name": "rescript-struct", + "name": "rescript-schema", "namespace": true, "suffix": ".bs.mjs", "package-specs": { diff --git a/docs/integration-guide.md b/docs/integration-guide.md index bb68111d..7d68b30b 100644 --- a/docs/integration-guide.md +++ b/docs/integration-guide.md @@ -1,7 +1,7 @@ [⬅ Back to highlights](../README.md) -# ReScript Struct for library maintainers +# ReScript Schema for library maintainers -If you're a library maintainer, you can use **rescript-struct** to get information about described structures. The most common use case is building type-safe schemas e.g for REST APIs, databases, and forms. +If you're a library maintainer, you can use **rescript-schema** as a building block for your tools. The most common use case is a type-safe schema for REST APIs, databases, forms, etc. Documentation for this feature is work in progress, for now, you can use `S.resi` file as a reference and the [rescript-json-schema](https://github.com/DZakh/rescript-json-schema)'s source code. diff --git a/docs/js-usage.md b/docs/js-usage.md index 646711bd..4a14a93e 100644 --- a/docs/js-usage.md +++ b/docs/js-usage.md @@ -1,6 +1,6 @@ [⬅ Back to highlights](../README.md) -# ReScript Struct for JS/TS users +# ReScript Schema for JS/TS users ## Table of contents @@ -16,22 +16,22 @@ - [Optionals](#optionals) - [Nullables](#nullables) - [Objects](#objects) - - [Advanced object struct](#advanced-object-struct) + - [Advanced object schema](#advanced-object-schema) - [`Object.strict`](#objectstrict) - [`Object.strip`](#objectstrip) - [`merge`](#merge) - [Arrays](#arrays) - [Tuples](#tuples) - - [Advanced tuple struct](#advanced-tuple-struct) + - [Advanced tuple schema](#advanced-tuple-schema) - [Unions](#unions) - [Records](#records) - [JSON](#json) - [JSON string](#json-string) - [Describe](#describe) -- [Custom structs](#custom-structs) +- [Custom schema](#custom-schema) - [Refinements](#refinements) - [Transforms](#transforms) -- [Functions on struct](#functions-on-struct) +- [Functions on schema](#functions-on-schema) - [`parse`](#parse) - [`parseOrThrow`](#parseorthrow) - [`parseAsync`](#parseasync) @@ -45,7 +45,7 @@ ## Install ```sh -npm install rescript-struct rescript@11 +npm install rescript-schema rescript@11 ``` > 🧠 Even though `rescript` is a peer dependency, you don't need to use the compiler. It's only needed for a few lightweight runtime helpers. @@ -53,22 +53,22 @@ npm install rescript-struct rescript@11 ## Basic usage ```ts -import * as S from "rescript-struct"; +import * as S from "rescript-schema"; -// Create login struct with email and password -const loginStruct = S.object({ +// Create login schema with email and password +const loginSchema = S.object({ email: S.String.email(S.string), password: S.String.min(S.string, 8), }); -// Infer output TypeScript type of login struct -type LoginData = S.Output; // { email: string; password: string } +// Infer output TypeScript type of login schema +type LoginData = S.Output; // { email: string; password: string } // Throws the S.Error(`Failed parsing at ["email"]. Reason: Invalid email address`) -S.parseOrThrow(loginStruct, { email: "", password: "" }); +S.parseOrThrow(loginSchema, { email: "", password: "" }); // Returns data as { email: string; password: string } -S.parseOrThrow(loginStruct, { +S.parseOrThrow(loginSchema, { email: "jane@example.com", password: "12345678", }); @@ -77,7 +77,7 @@ S.parseOrThrow(loginStruct, { ## Primitives ```ts -import * as S from "rescript-struct"; +import * as S from "rescript-schema"; // primitive values S.string; @@ -112,15 +112,15 @@ const terrificSymbol = Symbol("terrific"); const terrific = S.literal(terrificSymbol); ``` -Compared to other libraries, `S.literal` in **rescript-struct** supports literally any value. They are validated using strict equal checks. With the exception of plain objects and arrays, they are validated using deep equal checks. So the struct like this will work correctly: +Compared to other libraries, `S.literal` in **rescript-schema** supports literally any value. They are validated using strict equal checks. With the exception of plain objects and arrays, they are validated using deep equal checks. So the schema like this will work correctly: ```ts -const cliArgsStruct = S.literal(["help", "lint"] as const); +const cliArgsSchema = S.literal(["help", "lint"] as const); ``` ## Strings -**rescript-struct** includes a handful of string-specific refinements and transforms: +**rescript-schema** includes a handful of string-specific refinements and transforms: ```ts S.String.max(S.string, 5); // String must be 5 or fewer characters long @@ -148,19 +148,19 @@ S.String.length(S.string, 5, "SMS code should be 5 digits long"); The `S.String.datetime(S.string)` function has following UTC validation: no timezone offsets with arbitrary sub-second decimal precision. ```ts -const datetimeStruct = S.String.datetime(S.string); -// The datetimeStruct has the type S.Struct +const datetimeSchema = S.String.datetime(S.string); +// The datetimeSchema has the type S.Schema // String is transformed to the Date instance -S.parseOrThrow(datetimeStruct, "2020-01-01T00:00:00Z"); // pass -S.parseOrThrow(datetimeStruct, "2020-01-01T00:00:00.123Z"); // pass -S.parseOrThrow(datetimeStruct, "2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision) -S.parseOrThrow(datetimeStruct, "2020-01-01T00:00:00+02:00"); // fail (no offsets allowed) +S.parseOrThrow(datetimeSchema, "2020-01-01T00:00:00Z"); // pass +S.parseOrThrow(datetimeSchema, "2020-01-01T00:00:00.123Z"); // pass +S.parseOrThrow(datetimeSchema, "2020-01-01T00:00:00.123456Z"); // pass (arbitrary precision) +S.parseOrThrow(datetimeSchema, "2020-01-01T00:00:00+02:00"); // fail (no offsets allowed) ``` ## Numbers -**rescript-struct** includes some of number-specific refinements: +**rescript-schema** includes some of number-specific refinements: ```ts S.Number.max(S.number, 5); // Number must be lower than or equal to 5 @@ -175,32 +175,32 @@ S.Number.max(S.number, 5, "this👏is👏too👏big"); ## NaNs -There's no specific struct for NaN, but you can use `S.literal` for this. +There's no specific schema for NaN, but you can use `S.literal` for this. ```ts -const nanStruct = S.literal(NaN); +const nanSchema = S.literal(NaN); ``` It's going to use `Number.isNaN` check under the hood. ## Optionals -You can make any struct optional with `S.optional`. +You can make any schema optional with `S.optional`. ```ts -const struct = S.optional(S.string); +const schema = S.optional(S.string); -S.parseOrThrow(struct, undefined); // => returns undefined -type A = S.Output; // string | undefined +S.parseOrThrow(schema, undefined); // => returns undefined +type A = S.Output; // string | undefined ``` You can pass a default value to the second argument of `S.optional`. ```ts -const stringWithDefaultStruct = S.optional(S.string, "tuna"); +const stringWithDefaultSchema = S.optional(S.string, "tuna"); -S.parseOrThrow(stringWithDefaultStruct, undefined); // => returns "tuna" -type A = S.Output; // string +S.parseOrThrow(stringWithDefaultSchema, undefined); // => returns "tuna" +type A = S.Output; // string ``` Optionally, you can pass a function as a default value that will be re-executed whenever a default value needs to be generated: @@ -213,7 +213,7 @@ S.parseOrThrow(numberWithRandomDefault, undefined); // => 0.1871840107401901 S.parseOrThrow(numberWithRandomDefault, undefined); // => 0.7223408162401552 ``` -Conceptually, this is how **rescript-struct** processes default values: +Conceptually, this is how **rescript-schema** processes default values: 1. If the input is `undefined`, the default value is returned 2. Otherwise, the data is parsed using the base schema @@ -223,22 +223,22 @@ Conceptually, this is how **rescript-struct** processes default values: Similarly, you can create nullable types with `S.nullable`. ```ts -const nullableStringStruct = S.nullable(S.string); -S.parseOrThrow(nullableStringStruct, "asdf"); // => "asdf" -S.parseOrThrow(nullableStringStruct, null); // => null +const nullableStringSchema = S.nullable(S.string); +S.parseOrThrow(nullableStringSchema, "asdf"); // => "asdf" +S.parseOrThrow(nullableStringSchema, null); // => null ``` ## Objects ```ts // all properties are required by default -const dogStruct = S.object({ +const dogSchema = S.object({ name: S.string, age: S.number, }); // extract the inferred type like this -type Dog = S.Output; +type Dog = S.Output; // equivalent to: type Dog = { @@ -247,30 +247,30 @@ type Dog = { }; ``` -### Advanced object struct +### Advanced object schema -Sometimes you want to transform the data coming to your system. You can easily do it by passing a function to the `S.object` struct. +Sometimes you want to transform the data coming to your system. You can easily do it by passing a function to the `S.object` schema. ```ts -const userStruct = S.object((s) => ({ +const userSchema = S.object((s) => ({ id: s.field("USER_ID", S.number), name: s.field("USER_NAME", S.string), })); -S.parseOrThrow(userStruct, { +S.parseOrThrow(userSchema, { USER_ID: 1, USER_NAME: "John", }); // => returns { id: 1, name: "John" } -// Infer output TypeScript type of the userStruct -type User = S.Output; // { id: number; name: string } +// Infer output TypeScript type of the userSchema +type User = S.Output; // { id: number; name: string } ``` -Compared to using `S.transform`, the approach has 0 performance overhead. Also, you can use the same struct to transform the parsed data back to the initial format: +Compared to using `S.transform`, the approach has 0 performance overhead. Also, you can use the same schema to transform the parsed data back to the initial format: ```ts -S.serializeOrThrow(userStruct, { +S.serializeOrThrow(userSchema, { id: 1, name: "John", }); @@ -279,16 +279,16 @@ S.serializeOrThrow(userStruct, { ### `Object.strict` -By default **rescript-struct** object struct strip out unrecognized keys during parsing. You can disallow unknown keys with `S.Object.strict` function. If there are any unknown keys in the input, **rescript-struct** will fail with an error. +By default **rescript-schema** object schema strip out unrecognized keys during parsing. You can disallow unknown keys with `S.Object.strict` function. If there are any unknown keys in the input, **rescript-schema** will fail with an error. ```ts -const personStruct = S.Object.strict( +const personSchema = S.Object.strict( S.object({ name: S.string, }) ); -S.parseOrThrow(personStruct, { +S.parseOrThrow(personSchema, { name: "bob dylan", extraKey: 61, }); @@ -297,29 +297,29 @@ S.parseOrThrow(personStruct, { ### `Object.strip` -You can use the `S.Object.strip` function to reset an object struct to the default behavior (stripping unrecognized keys). +You can use the `S.Object.strip` function to reset an object schema to the default behavior (stripping unrecognized keys). ### `merge` You can add additional fields to an object schema with the `merge` function. ```ts -const baseTeacherStruct = S.object({ students: S.array(S.string) }); -const hasIDStruct = S.object({ id: S.string }); +const baseTeacherSchema = S.object({ students: S.array(S.string) }); +const hasIDSchema = S.object({ id: S.string }); -const teacherStruct = S.merge(baseTeacherStruct, hasIDStruct); -type Teacher = S.Output; // => { students: string[], id: string } +const teacherSchema = S.merge(baseTeacherSchema, hasIDSchema); +type Teacher = S.Output; // => { students: string[], id: string } ``` -> 🧠 The function will throw if the structs share keys. The returned schema also inherits the "unknownKeys" policy (strip/strict) of B. +> 🧠 The function will throw if the schemas share keys. The returned schema also inherits the "unknownKeys" policy (strip/strict) of B. ## Arrays ```ts -const stringArrayStruct = S.array(S.string); +const stringArraySchema = S.array(S.string); ``` -**rescript-struct** includes some of array-specific refinements: +**rescript-schema** includes some of array-specific refinements: ```ts S.Array.max(S.array(S.string), 5); // Array must be 5 or fewer items long @@ -332,7 +332,7 @@ S.Array.length(S.array(S.string) 5); // Array must be exactly 5 items long Unlike arrays, tuples have a fixed number of elements and each element can have a different type. ```ts -const athleteStruct = S.tuple([ +const athleteSchema = S.tuple([ S.string, // name S.number, // jersey number S.object({ @@ -340,16 +340,16 @@ const athleteStruct = S.tuple([ }), // statistics ]); -type Athlete = S.Output; +type Athlete = S.Output; // type Athlete = [string, number, { pointsScored: number }] ``` -### Advanced tuple struct +### Advanced tuple schema -Sometimes you want to transform incoming tuples to a more convenient data-structure. To do this you can pass a function to the `S.tuple` struct. +Sometimes you want to transform incoming tuples to a more convenient data-structure. To do this you can pass a function to the `S.tuple` schema. ```ts -const athleteStruct = S.tuple((s) => ({ +const athleteSchema = S.tuple((s) => ({ name: s.item(0, S.string), jerseyNumber: s.item(1, S.number), statistics: s.item( @@ -360,7 +360,7 @@ const athleteStruct = S.tuple((s) => ({ ), })); -type Athlete = S.Output; +type Athlete = S.Output; // type Athlete = { // name: string; // jerseyNumber: number; @@ -370,37 +370,37 @@ type Athlete = S.Output; // } ``` -That looks much better than before. And the same as for advanced objects, you can use the same struct for transforming the parsed data back to the initial format. Also, it has 0 performance overhead and is as fast as parsing tuples without the transformation. +That looks much better than before. And the same as for advanced objects, you can use the same schema for transforming the parsed data back to the initial format. Also, it has 0 performance overhead and is as fast as parsing tuples without the transformation. ## Unions -**rescript-struct** includes a built-in S.union struct for composing "OR" types. +**rescript-schema** includes a built-in S.union schema for composing "OR" types. ```ts -const stringOrNumberStruct = S.union([S.string, S.number]); +const stringOrNumberSchema = S.union([S.string, S.number]); -S.parseOrThrow(stringOrNumberStruct, "foo"); // passes -S.parseOrThrow(stringOrNumberStruct, 14); // passes +S.parseOrThrow(stringOrNumberSchema, "foo"); // passes +S.parseOrThrow(stringOrNumberSchema, 14); // passes ``` It will test the input against each of the "options" in order and return the first value that parses successfully. ## Records -Record structs are used to validate types such as `{ [k: string]: number }`. +Record schema is used to validate types such as `{ [k: string]: number }`. -If you want to validate the values of an object against some struct but don't care about the keys, use `S.record(valueStruct)`: +If you want to validate the values of an object against some schema but don't care about the keys, use `S.record(valueSchema)`: ```ts -const numberCacheStruct = S.record(S.number); +const numberCacheSchema = S.record(S.number); -type NumberCache = S.Output; +type NumberCache = S.Output; // => { [k: string]: number } ``` ## JSON -The `S.json` struct makes sure that the value is compatible with JSON. +The `S.json` schema makes sure that the value is compatible with JSON. ```ts S.parseOrThrow(S.json, "foo"); // passes @@ -409,50 +409,50 @@ S.parseOrThrow(S.json, "foo"); // passes ## JSON string ```ts -const struct = S.jsonString(S.int); +const schema = S.jsonString(S.int); -S.parseOrThrow("123", struct); +S.parseOrThrow("123", schema); // => 123 ``` -The `S.jsonString` struct represents JSON string containing value of a specific type. +The `S.jsonString` schema represents JSON string containing value of a specific type. ## Describe -Use `S.describe` to add a `description` property to the resulting struct. +Use `S.describe` to add a `description` property to the resulting schema. ```ts -const documentedStringStruct = S.describe( +const documentedStringSchema = S.describe( S.string, "A useful bit of text, if you know what to do with it." ); -S.description(documentedStringStruct); // A useful bit of text… +S.description(documentedStringSchema); // A useful bit of text… ``` This can be useful for documenting a field, for example in a JSON Schema using a library like [`rescript-json-schema`](https://github.com/DZakh/rescript-json-schema). -## Custom structs +## Custom schema -You can create a struct for any TypeScript type by using `S.custom`. This is useful for creating structs for types that are not supported by **rescript-struct** out of the box. +You can create a schema for any TypeScript type by using `S.custom`. This is useful for creating schema for types that are not supported by **rescript-schema** out of the box. ```ts -const mySetStruct = S.custom("MySet", (input, s) => { +const mySetSchema = S.custom("MySet", (input, s) => { if (input instanceof Set) { return input; } throw s.fail("Provided data is not an instance of Set."); }); -type MySet = S.Output; // Set +type MySet = S.Output; // Set ``` ## Refinements -**rescript-struct** lets you provide custom validation logic via refinements. It's useful to add checks that's not possible to cover with type system. For instance: checking that a number is an integer or that a string is a valid email address. +**rescript-schema** lets you provide custom validation logic via refinements. It's useful to add checks that's not possible to cover with type system. For instance: checking that a number is an integer or that a string is a valid email address. ```ts -const shortStringStruct = S.refine(S.string, (value, s) => +const shortStringSchema = S.refine(S.string, (value, s) => if (value.length > 255) { throw s.fail("String can't be more than 255 characters") } @@ -464,7 +464,7 @@ The refine function is applied for both parser and serializer. Also, you can have an asynchronous refinement (for parser only): ```ts -const userStruct = S.object({ +const userSchema = S.object({ id: S.asyncParserRefine(S.String.uuid(S.string), async (id, s) => { const isActiveUser = await checkIsActiveUser(id); if (!isActiveUser) { @@ -474,10 +474,10 @@ const userStruct = S.object({ name: S.string, }); -type User = S.Output; // { id: string, name: string } +type User = S.Output; // { id: string, name: string } // Need to use parseAsync which will return a promise with S.Result -await S.parseAsync(userStruct, { +await S.parseAsync(userSchema, { id: "1", name: "John", }); @@ -485,12 +485,12 @@ await S.parseAsync(userStruct, { ## Transforms -**rescript-struct** allows structs to be augmented with transformation logic, letting you transform value during parsing and serializing. This is most commonly used for mapping value to more convenient data structures. +**rescript-schema** allows to augment schema with transformation logic, letting you transform value during parsing and serializing. This is most commonly used for mapping value to more convenient data-structures. ```ts -const intToString = (struct) => +const intToString = (schema) => S.transform( - struct, + schema, (int) => int.toString(), (string, s) => { const int = parseInt(string, 10); @@ -502,20 +502,20 @@ const intToString = (struct) => ); ``` -## Functions on struct +## Functions on schema ### **`parse`** ```ts -S.parse(struct, data); // => S.Result +S.parse(schema, data); // => S.Result ``` -Given any struct, you can call `S.parse` to check `data` is valid. It returns `S.Result` with valid data transformed to expected type or a **rescript-struct** error. +Given any schema, you can call `S.parse` to check `data` is valid. It returns `S.Result` with valid data transformed to expected type or a **rescript-schema** error. ### **`parseOrThrow`** ```ts -S.parseOrThrow(struct, data); // => Output +S.parseOrThrow(schema, data); // => Output // Or throws S.Error ``` @@ -524,7 +524,7 @@ The exception-based version of `S.parse`. ### **`parseAsync`** ```ts -await S.parseAsync(struct, data); // => S.Result +await S.parseAsync(schema, data); // => S.Result ``` If you use asynchronous refinements or transforms, you'll need to use `parseAsync`. It will parse all synchronous branches first and then continue with asynchronous refinements and transforms in parallel. @@ -532,15 +532,15 @@ If you use asynchronous refinements or transforms, you'll need to use `parseAsyn ### **`serialize`** ```ts -S.serialize(userStruct, user); // => S.Result +S.serialize(userSchema, user); // => S.Result ``` -Serializes value using the transformation logic that is built-in to the struct. It returns a result with a transformed data or a **rescript-struct** error. +Serializes value using the transformation logic that is built-in to the schema. It returns a result with a transformed data or a **rescript-schema** error. ### **`serializeOrThrow`** ```ts -S.serializeOrThrow(userStruct, user); // => Input +S.serializeOrThrow(userSchema, user); // => Input // Or throws S.Error ``` @@ -560,17 +560,17 @@ Used internally for readable error messages. ### **`setName`** ```ts -const struct = S.setName(S.literal({ abc: 123 }, "Abc")); +const schema = S.setName(S.literal({ abc: 123 }, "Abc")); -S.name(struct); +S.name(schema); // `Abc` ``` -You can customise a struct name using `S.setName`. +You can customise a schema name using `S.setName`. ## Error handling -**rescript-struct** provides a subclass of Error called `S.Error`. It contains detailed information about the validation problem. +**rescript-schema** provides a subclass of Error called `S.Error`. It contains detailed information about the validation problem. ```ts S.parseOrThrow(S.literal(false), true); @@ -579,20 +579,20 @@ S.parseOrThrow(S.literal(false), true); ## Comparison -Instead of relying on a few large functions with many methods, **rescript-struct** follows [Valibot](https://github.com/fabian-hiller/valibot)'s approach, where API design and source code is based on many small and independent functions, each with just a single task. This modular design has several advantages. +Instead of relying on a few large functions with many methods, **rescript-schema** follows [Valibot](https://github.com/fabian-hiller/valibot)'s approach, where API design and source code is based on many small and independent functions, each with just a single task. This modular design has several advantages. For example, this allows a bundler to use the import statements to remove code that is not needed. This way, only the code that is actually used gets into your production build. This can reduce the bundle size by up to 2 times compared to [Zod](https://github.com/colinhacks/zod). Besides the individual bundle size, the overall size of the library is also significantly smaller. -At the same time **rescript-struct** is the fastest composable validation library in the entire JavaScript ecosystem. This is achieved because of the JIT approach when an ultra optimized validator is created using `eval`. +At the same time **rescript-schema** is the fastest composable validation library in the entire JavaScript ecosystem. This is achieved because of the JIT approach when an ultra optimized validator is created using `eval`. -| | rescript-struct@5.1.0 | Zod@3.22.2 | Valibot@0.18.0 | +| | rescript-schema@5.1.0 | Zod@3.22.2 | Valibot@0.18.0 | | ------------------------------------------------ | --------------------- | --------------- | -------------- | | **Total size** (minified + gzipped) | 9.67 kB | 13.4 kB | 6.73 kB | | **Example size** (minified + gzipped) | 5.53 kB | 12.8 kB | 965 B | | **Nested object parsing** | 153,787 ops/ms | 1,177 ops/ms | 3,562 ops/ms | -| **Create struct/schema + Nested object parsing** | 54 ops/ms | 110 ops/ms | 1,937 ops/ms | +| **Create schema/schema + Nested object parsing** | 54 ops/ms | 110 ops/ms | 1,937 ops/ms | | **Eval-free** | ❌ | ✅ | ✅ | | **Codegen-free** (Doesn't need compiler) | ✅ | ✅ | ✅ | | **Ecosystem** | ⭐️ | ⭐️⭐️⭐️⭐️⭐️ | ⭐️⭐️ | diff --git a/docs/rescript-usage.md b/docs/rescript-usage.md index 077f7f45..76eeb0f0 100644 --- a/docs/rescript-usage.md +++ b/docs/rescript-usage.md @@ -1,6 +1,6 @@ [⬅ Back to highlights](../README.md) -# ReScript Struct for ReScript users +# ReScript Schema for ReScript users ## Table of contents @@ -8,7 +8,7 @@ - [Install](#install) - [Basic usage](#basic-usage) - [Real-world examples](#real-world-examples) -- [Structs](#structs) +- [API](#api) - [`string`](#string) - [ISO datetimes](#iso-datetimes) - [`bool`](#bool) @@ -47,7 +47,7 @@ - [Refinements](#refinements) - [Transforms](#transforms) - [Preprocess](#preprocess-advanced) -- [Functions on struct](#functions-on-struct) +- [Functions on schema](#functions-on-schema) - [`parseWith`](#parsewith) - [`parseAnyWith`](#parseanywith) - [`parseJsonStringWith`](#parsejsonstringwith) @@ -71,20 +71,20 @@ ## Install ```sh -npm install rescript-struct +npm install rescript-schema ``` -Then add `rescript-struct` to `bs-dependencies` in your `bsconfig.json`: +Then add `rescript-schema` to `bs-dependencies` in your `bsconfig.json`: ```diff { ... -+ "bs-dependencies": ["rescript-struct"], -+ "bsc-flags": ["-open RescriptStruct"], ++ "bs-dependencies": ["rescript-schema"], ++ "bsc-flags": ["-open RescriptSchema"], } ``` -> 🧠 Starting from V5 **rescript-struct** requires **rescript@11**. At the same time it works in both curried and uncurried mode. +> 🧠 Starting from V5 **rescript-schema** requires **rescript@11**. At the same time it works in both curried and uncurried mode. ## Basic usage @@ -103,8 +103,8 @@ type film = { deprecatedAgeRestriction: option, } -// 2. Create a struct -let filmStruct = S.object(s => { +// 2. Create a schema +let filmSchema = S.object(s => { id: s.field("Id", S.float), title: s.field("Title", S.string), tags: s.fieldOr("Tags", S.array(S.string), []), @@ -120,14 +120,14 @@ let filmStruct = S.object(s => { deprecatedAgeRestriction: s.field("Age", S.option(S.int)->S.deprecate("Use rating instead")), }) -// 3. Parse data using the struct +// 3. Parse data using the schema // The data is validated and transformed to a convenient format %raw(`{ "Id": 1, "Title": "My first film", "Rating": "R", "Age": 17 -}`)->S.parseWith(filmStruct) +}`)->S.parseWith(filmSchema) // Ok({ // id: 1., // title: "My first film", @@ -136,14 +136,14 @@ let filmStruct = S.object(s => { // deprecatedAgeRestriction: Some(17), // }) -// 4. Transform data back using the same struct +// 4. Transform data back using the same schema { id: 2., tags: ["Loved"], title: "Sad & sed", rating: ParentalStronglyCautioned, deprecatedAgeRestriction: None, -}->S.serializeWith(filmStruct) +}->S.serializeWith(filmSchema) // Ok(%raw(`{ // "Id": 2, // "Title": "Sad & sed", @@ -152,9 +152,9 @@ let filmStruct = S.object(s => { // "Age": undefined, // }`)) -// 5. Use struct as a building block for other tools +// 5. Use schema as a building block for other tools // For example, create a JSON-schema with rescript-json-schema and use it for OpenAPI generation -let filmJsonSchema = JSONSchema.make(filmStruct) +let filmJsonSchema = JSONSchema.make(filmSchema) ``` ## Real-world examples @@ -163,22 +163,22 @@ let filmJsonSchema = JSONSchema.make(filmStruct) - [Creating CLI utility](https://github.com/DZakh/rescript-stdlib-cli/blob/main/src/interactors/RunCli.res) - [Safely accessing environment variables](https://github.com/Nicolas1st/net-cli-rock-paper-scissors/blob/main/apps/client/src/Env.res) -## Structs +## API ### **`string`** `S.t` ```rescript -let struct = S.string +let schema = S.string -%raw(`"Hello World!"`)->S.parseWith(struct) +%raw(`"Hello World!"`)->S.parseWith(schema) // Ok("Hello World!") ``` -The `string` struct represents a data that is a string. It can be further constrainted with the following utility methods. +The `string` schema represents a data that is a string. It can be further constrainted with the following utility methods. -**rescript-struct** includes a handful of string-specific refinements and transforms: +**rescript-schema** includes a handful of string-specific refinements and transforms: ```rescript S.string->S.String.max(5) // String must be 5 or fewer characters long @@ -206,14 +206,14 @@ S.string->S.String.length(5, ~message="SMS code should be 5 digits long") The `S.string->S.String.datetime` function has following UTC validation: no timezone offsets with arbitrary sub-second decimal precision. ```rescript -let datetimeStruct = S.string->S.String.datetime -// The datetimeStruct has the type S.t +let datetimeSchema = S.string->S.String.datetime +// The datetimeSchema has the type S.t // String is transformed to the Date.t instance -%raw(`"2020-01-01T00:00:00Z"`)->S.parseWith(datetimeStruct) // pass -%raw(`"2020-01-01T00:00:00.123Z"`)->S.parseWith(datetimeStruct) // pass -%raw(`"2020-01-01T00:00:00.123456Z"`)->S.parseWith(datetimeStruct) // pass (arbitrary precision) -%raw(`"2020-01-01T00:00:00+02:00"`)->S.parseWith(datetimeStruct) // fail (no offsets allowed) +%raw(`"2020-01-01T00:00:00Z"`)->S.parseWith(datetimeSchema) // pass +%raw(`"2020-01-01T00:00:00.123Z"`)->S.parseWith(datetimeSchema) // pass +%raw(`"2020-01-01T00:00:00.123456Z"`)->S.parseWith(datetimeSchema) // pass (arbitrary precision) +%raw(`"2020-01-01T00:00:00+02:00"`)->S.parseWith(datetimeSchema) // fail (no offsets allowed) ``` ### **`bool`** @@ -221,28 +221,28 @@ let datetimeStruct = S.string->S.String.datetime `S.t` ```rescript -let struct = S.bool +let schema = S.bool -%raw(`false`)->S.parseWith(struct) +%raw(`false`)->S.parseWith(schema) // Ok(false) ``` -The `bool` struct represents a data that is a boolean. +The `bool` schema represents a data that is a boolean. ### **`int`** `S.t` ```rescript -let struct = S.int +let schema = S.int -%raw(`123`)->S.parseWith(struct) +%raw(`123`)->S.parseWith(schema) // Ok(123) ``` -The `int` struct represents a data that is an integer. +The `int` schema represents a data that is an integer. -**rescript-struct** includes some of int-specific refinements: +**rescript-schema** includes some of int-specific refinements: ```rescript S.int->S.Int.max(5) // Number must be lower than or equal to 5 @@ -255,15 +255,15 @@ S.int->S.Int.port // Invalid port `S.t` ```rescript -let struct = S.float +let schema = S.float -%raw(`123`)->S.parseWith(struct) +%raw(`123`)->S.parseWith(schema) // Ok(123.) ``` -The `float` struct represents a data that is a number. +The `float` schema represents a data that is a number. -**rescript-struct** includes some of float-specific refinements: +**rescript-schema** includes some of float-specific refinements: ```rescript S.float->S.Float.max(5) // Number must be lower than or equal to 5 @@ -275,30 +275,30 @@ S.float->S.Float.min(5) // Number must be greater than or equal to 5 `S.t<'value> => S.t>` ```rescript -let struct = S.option(S.string) +let schema = S.option(S.string) -%raw(`"Hello World!"`)->S.parseWith(struct) +%raw(`"Hello World!"`)->S.parseWith(schema) // Ok(Some("Hello World!")) -%raw(`undefined`)->S.parseWith(struct) +%raw(`undefined`)->S.parseWith(schema) // Ok(None) ``` -The `option` struct represents a data of a specific type that might be undefined. +The `option` schema represents a data of a specific type that might be undefined. ### **`Option.getOr`** `(S.t>, 'value) => S.t<'value>` ```rescript -let struct = S.option(S.string)->S.Option.getOr("Hello World!") +let schema = S.option(S.string)->S.Option.getOr("Hello World!") -%raw(`undefined`)->S.parseWith(struct) +%raw(`undefined`)->S.parseWith(schema) // Ok("Hello World!") -%raw(`"Goodbye World!"`)->S.parseWith(struct) +%raw(`"Goodbye World!"`)->S.parseWith(schema) // Ok("Goodbye World!") ``` -The `Option.getOr` augments a struct to add transformation logic for default values, which are applied when the input is undefined. +The `Option.getOr` augments a schema to add transformation logic for default values, which are applied when the input is undefined. > 🧠 If you want to set a default value for an object field, there's a more convenient `fieldOr` method on `Object.ctx` type. @@ -307,11 +307,11 @@ The `Option.getOr` augments a struct to add transformation logic for default val `(S.t>, () => 'value) => S.t<'value>` ```rescript -let struct = S.option(S.array(S.string))->S.Option.getOrWith(() => ["Hello World!"]) +let schema = S.option(S.array(S.string))->S.Option.getOrWith(() => ["Hello World!"]) -%raw(`undefined`)->S.parseWith(struct) +%raw(`undefined`)->S.parseWith(schema) // Ok(["Hello World!"]) -%raw(`["Goodbye World!"]`)->S.parseWith(struct) +%raw(`["Goodbye World!"]`)->S.parseWith(schema) // Ok(["Goodbye World!"]) ``` @@ -322,15 +322,15 @@ Also you can use `Option.getOrWith` for lazy evaluation of the default value. `S.t<'value> => S.t>` ```rescript -let struct = S.null(S.string) +let schema = S.null(S.string) -%raw(`"Hello World!"`)->S.parseWith(struct) +%raw(`"Hello World!"`)->S.parseWith(schema) // Ok(Some("Hello World!")) -%raw(`null`)->S.parseWith(struct) +%raw(`null`)->S.parseWith(schema) // Ok(None) ``` -The `null` struct represents a data of a specific type that might be null. +The `null` schema represents a data of a specific type that might be null. > 🧠 Since `null` transforms value into `option` type, you can use `Option.getOr`/`Option.getOrWith` for it as well. @@ -339,48 +339,48 @@ The `null` struct represents a data of a specific type that might be null. `S.t` ```rescript -let struct = S.unit +let schema = S.unit -%raw(`undefined`)->S.parseWith(struct) +%raw(`undefined`)->S.parseWith(schema) // Ok() ``` -The `unit` struct factory is an alias for `S.literal()`. +The `unit` schema factory is an alias for `S.literal()`. ### **`literal`** `'value => S.t<'value>` ```rescript -let tunaStruct = S.literal("Tuna") -let twelveStruct = S.literal(12) -let importantTimestampStruct = S.literal(1652628345865.) -let truStruct = S.literal(true) -let nullStruct = S.literal(Null.null) -let undefinedStruct = S.literal() // Building block for S.unit +let tunaSchema = S.literal("Tuna") +let twelveSchema = S.literal(12) +let importantTimestampSchema = S.literal(1652628345865.) +let truSchema = S.literal(true) +let nullSchema = S.literal(Null.null) +let undefinedSchema = S.literal() // Building block for S.unit // Uses Number.isNaN to match NaN literals -let nanStruct = S.literal(Float.Constants.nan)->S.variant(_ => ()) // For NaN literals I recomment adding S.variant to transform it to unit. It's better than having it as a float +let nanSchema = S.literal(Float.Constants.nan)->S.variant(_ => ()) // For NaN literals I recomment adding S.variant to transform it to unit. It's better than having it as a float // Supports symbols and BigInt -let symbolStruct = S.literal(Symbol.asyncIterator) -let twobigStruct = S.literal(BigInt.fromInt(2)) +let symbolSchema = S.literal(Symbol.asyncIterator) +let twobigSchema = S.literal(BigInt.fromInt(2)) // Supports variants and polymorphic variants -let appleStruct = S.literal(#apple) -let noneStruct = S.literal(None) +let appleSchema = S.literal(#apple) +let noneSchema = S.literal(None) // Does a deep check for plain objects and arrays -let cliArgsStruct = S.literal(("help", "lint")) +let cliArgsSchema = S.literal(("help", "lint")) // Supports functions and literally any Js values matching them with the === operator let fn = () => "foo" -let fnStruct = S.literal(fn) +let fnSchema = S.literal(fn) let weakMap = WeakMap.make() -let weakMapStruct = S.literal(weakMap) +let weakMapSchema = S.literal(weakMap) ``` -The `literal` struct enforces that a data matches an exact value during parsing and serializing. +The `literal` schema enforces that a data matches an exact value during parsing and serializing. ### **`object`** @@ -392,18 +392,18 @@ type point = { y: int, } -// The pointStruct will have the S.t type -let pointStruct = S.object(s => { +// The pointSchema will have the S.t type +let pointSchema = S.object(s => { x: s.field("x", S.int), y: s.field("y", S.int), }) // It can be used both for parsing and serializing -%raw(`{ "x": 1,"y": -4 }`)->S.parseWith(pointStruct) -{ x: 1, y: -4 }->S.serializeWith(pointStruct) +%raw(`{ "x": 1,"y": -4 }`)->S.parseWith(pointSchema) +{ x: 1, y: -4 }->S.serializeWith(pointSchema) ``` -The `object` struct represents an object value, that can be transformed into any ReScript value. Here are some examples: +The `object` schema represents an object value, that can be transformed into any ReScript value. Here are some examples: #### Transform object field names @@ -413,12 +413,12 @@ type user = { name: string, } // It will have the S.t type -let struct = S.object(s => { +let schema = S.object(s => { id: s.field("USER_ID", S.int), name: s.field("USER_NAME", S.string), }) -%raw(`{"USER_ID":1,"USER_NAME":"John"}`)->S.parseWith(struct) +%raw(`{"USER_ID":1,"USER_NAME":"John"}`)->S.parseWith(schema) // Ok({ id: 1, name: "John" }) ``` @@ -426,7 +426,7 @@ let struct = S.object(s => { ```rescript // It will have the S.t<{"key1":string,"key2":string}> type -let struct = S.object(s => { +let schema = S.object(s => { "key1": s.field("key1", S.string), "key2": s.field("key2", S.string), }) @@ -436,16 +436,16 @@ let struct = S.object(s => { ```rescript // It will have the S.t<(int, string)> type -let struct = S.object(s => (s.field("USER_ID", S.int), s.field("USER_NAME", S.string))) +let schema = S.object(s => (s.field("USER_ID", S.int), s.field("USER_NAME", S.string))) -%raw(`{"USER_ID":1,"USER_NAME":"John"}`)->S.parseWith(struct) +%raw(`{"USER_ID":1,"USER_NAME":"John"}`)->S.parseWith(schema) // Ok((1, "John")) ``` -The same struct also works for serializing: +The same schema also works for serializing: ```rescript -(1, "John")->S.serializeWith(struct) +(1, "John")->S.serializeWith(schema) // Ok(%raw(`{"USER_ID":1,"USER_NAME":"John"}`)) ``` @@ -455,7 +455,7 @@ The same struct also works for serializing: type shape = Circle({radius: float}) | Square({x: float}) | Triangle({x: float, y: float}) // It will have the S.t type -let struct = S.object(s => { +let schema = S.object(s => { s.tag("kind", "circle") Circle({ radius: s.field("radius", S.float), @@ -465,14 +465,14 @@ let struct = S.object(s => { %raw(`{ "kind": "circle", "radius": 1, -}`)->S.parseWith(struct) +}`)->S.parseWith(schema) // Ok(Circle({radius: 1})) ``` -The same struct also works for serializing: +The same schema also works for serializing: ```rescript -Circle({radius: 1})->S.serializeWith(struct) +Circle({radius: 1})->S.serializeWith(schema) // Ok(%raw(`{ // "kind": "circle", // "radius": 1, @@ -485,11 +485,11 @@ Circle({radius: 1})->S.serializeWith(struct) ```rescript // Represents an object without fields -let struct = S.object(_ => ())->S.Object.strict +let schema = S.object(_ => ())->S.Object.strict %raw(`{ "someField": "value", -}`)->S.parseWith(struct) +}`)->S.parseWith(schema) // Error({ // code: ExcessField("someField"), // operation: Parsing, @@ -497,7 +497,7 @@ let struct = S.object(_ => ())->S.Object.strict // }) ``` -By default **rescript-struct** silently strips unrecognized keys when parsing objects. You can change the behaviour to disallow unrecognized keys with the `S.Object.strict` function. +By default **rescript-schema** silently strips unrecognized keys when parsing objects. You can change the behaviour to disallow unrecognized keys with the `S.Object.strict` function. ### **`Object.strip`** @@ -505,15 +505,15 @@ By default **rescript-struct** silently strips unrecognized keys when parsing ob ```rescript // Represents an object with any fields -let struct = S.object(_ => ())->S.Object.strip +let schema = S.object(_ => ())->S.Object.strip %raw(`{ "someField": "value", -}`)->S.parseWith(struct) +}`)->S.parseWith(schema) // Ok() ``` -You can use the `S.Object.strip` function to reset a object struct to the default behavior (stripping unrecognized keys). +You can use the `S.Object.strip` function to reset a object schema to the default behavior (stripping unrecognized keys). ### **`variant`** @@ -523,16 +523,16 @@ You can use the `S.Object.strip` function to reset a object struct to the defaul type shape = Circle({radius: float}) | Square({x: float}) | Triangle({x: float, y: float}) // It will have the S.t type -let struct = S.float->S.variant(radius => Circle({radius: radius})) +let schema = S.float->S.variant(radius => Circle({radius: radius})) -%raw(`1`)->S.parseWith(struct) +%raw(`1`)->S.parseWith(schema) // Ok(Circle({radius: 1.})) ``` -The same struct also works for serializing: +The same schema also works for serializing: ```rescript -Circle({radius: 1})->S.serializeWith(struct) +Circle({radius: 1})->S.serializeWith(schema) // Ok(%raw(`1`)) ``` @@ -548,7 +548,7 @@ Circle({radius: 1})->S.serializeWith(struct) // | { kind: "triangle"; x: number; y: number }; type shape = Circle({radius: float}) | Square({x: float}) | Triangle({x: float, y: float}) -let shapeStruct = S.union([ +let shapeSchema = S.union([ S.object(s => { s.tag("kind", "circle") Circle({ @@ -575,19 +575,19 @@ let shapeStruct = S.union([ %raw(`{ "kind": "circle", "radius": 1, -}`)->S.parseWith(shapeStruct) +}`)->S.parseWith(shapeSchema) // Ok(Circle({radius: 1.})) ``` ```rescript -Square({x: 2.})->S.serializeWith(shapeStruct) +Square({x: 2.})->S.serializeWith(shapeSchema) // Ok({ // "kind": "square", // "x": 2, // }) ``` -The `union` will test the input against each of the structs in order and return the first value that validates successfully. +The `union` will test the input against each of the schemas in order and return the first value that validates successfully. #### Enums @@ -596,13 +596,13 @@ Also, you can describe enums using `S.union` together with `S.literal`. ```rescript type outcome = | @as("win") Win | @as("draw") Draw | @as("loss") Loss -let struct = S.union([ +let schema = S.union([ S.literal(Win), S.literal(Draw), S.literal(Loss), ]) -%raw(`"draw"`)->S.parseWith(struct) +%raw(`"draw"`)->S.parseWith(schema) // Ok(Draw) ``` @@ -611,20 +611,20 @@ let struct = S.union([ `S.t<'value> => S.t>` ```rescript -let struct = S.array(S.string) +let schema = S.array(S.string) -%raw(`["Hello", "World"]`)->S.parseWith(struct) +%raw(`["Hello", "World"]`)->S.parseWith(schema) // Ok(["Hello", "World"]) ``` -The `array` struct represents an array of data of a specific type. +The `array` schema represents an array of data of a specific type. -**rescript-struct** includes some of array-specific refinements: +**rescript-schema** includes some of array-specific refinements: ```rescript -S.array(itemStruct)->S.Array.max(5) // Array must be 5 or fewer items long -S.array(itemStruct)->S.Array.min(5) // Array must be 5 or more items long -S.array(itemStruct)->S.Array.length(5) // Array must be exactly 5 items long +S.array(itemSchema)->S.Array.max(5) // Array must be 5 or fewer items long +S.array(itemSchema)->S.Array.min(5) // Array must be 5 or more items long +S.array(itemSchema)->S.Array.length(5) // Array must be exactly 5 items long ``` ### **`list`** @@ -632,13 +632,13 @@ S.array(itemStruct)->S.Array.length(5) // Array must be exactly 5 items long `S.t<'value> => S.t>` ```rescript -let struct = S.list(S.string) +let schema = S.list(S.string) -%raw(`["Hello", "World"]`)->S.parseWith(struct) +%raw(`["Hello", "World"]`)->S.parseWith(schema) // Ok(list{"Hello", "World"}) ``` -The `list` struct represents an array of data of a specific type which is transformed to ReScript's list data structure. +The `list` schema represents an array of data of a specific type which is transformed to ReScript's list data-structure. ### **`tuple`** @@ -650,8 +650,8 @@ type point = { y: int, } -// The pointStruct will have the S.t type -let pointStruct = S.tuple(s => { +// The pointSchema will have the S.t type +let pointSchema = S.tuple(s => { s.tag(0, "point") { x: s.item(1, S.int), @@ -660,11 +660,11 @@ let pointStruct = S.tuple(s => { }) // It can be used both for parsing and serializing -%raw(`["point", 1, -4]`)->S.parseWith(pointStruct) -{ x: 1, y: -4 }->S.serializeWith(pointStruct) +%raw(`["point", 1, -4]`)->S.parseWith(pointSchema) +{ x: 1, y: -4 }->S.serializeWith(pointSchema) ``` -The `tuple` struct represents that a data is an array of a specific length with values each of a specific type. +The `tuple` schema represents that a data is an array of a specific length with values each of a specific type. For short tuples without the need for transformation, there are wrappers over `S.tuple`: @@ -673,9 +673,9 @@ For short tuples without the need for transformation, there are wrappers over `S `(S.t<'v0>, S.t<'v1>, S.t<'v2>) => S.t<('v0, 'v1, 'v2)>` ```rescript -let struct = S.tuple3(S.string, S.int, S.bool) +let schema = S.tuple3(S.string, S.int, S.bool) -%raw(`["a", 1, true]`)->S.parseWith(struct) +%raw(`["a", 1, true]`)->S.parseWith(schema) // Ok("a", 1, true) ``` @@ -684,37 +684,37 @@ let struct = S.tuple3(S.string, S.int, S.bool) `S.t<'value> => S.t>` ```rescript -let struct = S.dict(S.string) +let schema = S.dict(S.string) %raw(`{ "foo": "bar", "baz": "qux", -}`)->S.parseWith(struct) +}`)->S.parseWith(schema) // Ok(Dict.fromArray([("foo", "bar"), ("baz", "qux")])) ``` -The `dict` struct represents a dictionary of data of a specific type. +The `dict` schema represents a dictionary of data of a specific type. ### **`unknown`** `S.t` ```rescript -let struct = S.unknown +let schema = S.unknown -%raw(`"Hello World!"`)->S.parseWith(struct) +%raw(`"Hello World!"`)->S.parseWith(schema) ``` -The `unknown` struct represents any data. +The `unknown` schema represents any data. ### **`never`** `S.t` ```rescript -let struct = S.never +let schema = S.never -%raw(`undefined`)->S.parseWith(struct) +%raw(`undefined`)->S.parseWith(schema) // Error({ // code: InvalidType({expected: S.never, received: undefined}), // operation: Parsing, @@ -722,45 +722,45 @@ let struct = S.never // }) ``` -The `never` struct will fail parsing for every value. +The `never` schema will fail parsing for every value. ### **`json`** `S.t` ```rescript -let struct = S.json +let schema = S.json -%raw(`"123"`)->S.parseWith(struct) +%raw(`"123"`)->S.parseWith(schema) // Ok(String("123")) ``` -The `json` struct represents a data that is compatible with JSON. +The `json` schema represents a data that is compatible with JSON. ### **`jsonString`** `S.t<'value> => S.t<'value>` ```rescript -let struct = S.jsonString(S.int) +let schema = S.jsonString(S.int) -%raw(`"123"`)->S.parseWith(struct) +%raw(`"123"`)->S.parseWith(schema) // Ok(123) ``` -The `jsonString` struct represents JSON string containing value of a specific type. +The `jsonString` schema represents JSON string containing value of a specific type. ### **`describe`** `(S.t<'value>, string) => S.t<'value>` -Use `S.describe` to add a `description` property to the resulting struct. +Use `S.describe` to add a `description` property to the resulting schema. ```rescript -let documentedStringStruct = S.string +let documentedStringSchema = S.string ->S.describe("A useful bit of text, if you know what to do with it.") -documentedStringStruct->S.description // A useful bit of text… +documentedStringSchema->S.description // A useful bit of text… ``` This can be useful for documenting a field, for example in a JSON Schema using a library like [`rescript-json-schema`](https://github.com/DZakh/rescript-json-schema). @@ -769,7 +769,7 @@ This can be useful for documenting a field, for example in a JSON Schema using a `(S.t<'value>, string) => S.t<'value>` -Use `S.deprecate` to add a `deprecation` message property to the resulting struct. +Use `S.deprecate` to add a `deprecation` message property to the resulting schema. ```rescript let deprecatedString = S.string @@ -787,43 +787,43 @@ This can be useful for documenting a field, for example in a JSON Schema using a Use `S.catch` to provide a "catch value" to be returned instead of a parsing error. ```rescript -let struct = S.float->S.catch(_ => 42.) +let schema = S.float->S.catch(_ => 42.) -%raw(`5`)->S.parseWith(struct) +%raw(`5`)->S.parseWith(schema) // Ok(5.) -%raw(`"tuna"`)->S.parseWith(struct) +%raw(`"tuna"`)->S.parseWith(schema) // Ok(42.) ``` Also, the callback `S.catch` receives a catch context as a first argument. It contains the caught error and the initial data provided to the parse function. ```rescript -let struct = S.float->S.catch(s => { +let schema = S.float->S.catch(s => { Console.log(s.error) // The caught error Console.log(s.input) // The data provided to the parse function 42. }) ``` -Conceptually, this is how **rescript-struct** processes "catch values": +Conceptually, this is how **rescript-schema** processes "catch values": -1. The data is parsed using the base struct +1. The data is parsed using the base schema 2. If the parsing fails, the "catch value" is returned ### **`custom`** `(string, effectCtx<'output> => customDefinition<'input, 'output>) => t<'output>` -You can also define your own custom struct factories that are specific to your application's requirements: +You can also define your own custom schema factories that are specific to your application's requirements: ```rescript -let nullableStruct = innerStruct => { +let nullableSchema = innerSchema => { S.custom("Nullable", s => { parser: unknown => { if unknown === %raw(`undefined`) || unknown === %raw(`null`) { None } else { - switch unknown->S.parseAnyWith(innerStruct) { + switch unknown->S.parseAnyWith(innerSchema) { | Ok(value) => Some(value) | Error(error) => s.failWithError(error) } @@ -832,7 +832,7 @@ let nullableStruct = innerStruct => { serializer: value => { switch value { | Some(innerValue) => - switch innerValue->S.serializeToUnknownWith(innerStruct) { + switch innerValue->S.serializeToUnknownWith(innerSchema) { | Ok(value) => value | Error(error) => s.failWithError(error) } @@ -842,13 +842,13 @@ let nullableStruct = innerStruct => { }) } -%raw(`"Hello world!"`)->S.parseWith(struct) +%raw(`"Hello world!"`)->S.parseWith(schema) // Ok(Some("Hello World!")) -%raw(`null`)->S.parseWith(struct) +%raw(`null`)->S.parseWith(schema) // Ok(None) -%raw(`undefined`)->S.parseWith(struct) +%raw(`undefined`)->S.parseWith(schema) // Ok(None) -%raw(`123`)->S.parseWith(struct) +%raw(`123`)->S.parseWith(schema) // Error({ // code: InvalidType({expected: S.string, received: 123}), // operation: Parsing, @@ -860,7 +860,7 @@ let nullableStruct = innerStruct => { `(t<'value> => t<'value>) => t<'value>` -You can define a recursive struct in **rescript-struct**. +You can define a recursive schema in **rescript-schema**. ```rescript type rec node = { @@ -868,10 +868,10 @@ type rec node = { children: array, } -let nodeStruct = S.recursive(nodeStruct => { +let nodeSchema = S.recursive(nodeSchema => { S.object(s => { id: s.field("Id", S.string), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }) }) ``` @@ -883,20 +883,20 @@ let nodeStruct = S.recursive(nodeStruct => { {"Id": "2", "Children": []}, {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], -}`)->S.parseWith(nodeStruct) +}`)->S.parseWith(nodeSchema) // Ok({ // id: "1", // children: [{id: "2", children: []}, {id: "3", children: [{id: "4", children: []}]}], // }) ``` -The same struct works for serializing: +The same schema works for serializing: ```rescript { id: "1", children: [{id: "2", children: []}, {id: "3", children: [{id: "4", children: []}]}], -}->S.serializeWith(nodeStruct) +}->S.serializeWith(nodeSchema) // Ok(%raw(`{ // "Id": "1", // "Children": [ @@ -909,28 +909,28 @@ The same struct works for serializing: You can also use asynchronous parser: ```rescript -let nodeStruct = S.recursive(nodeStruct => { +let nodeSchema = S.recursive(nodeSchema => { S.object(s => { params: s.field("Id", S.string)->S.transform(_ => {asyncParser: id => () => loadParams(id)}), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }) }) ``` One great aspect of the example above is that it uses parallelism to make four requests to check for the existence of nodes. -> 🧠 Despite supporting recursive structs, passing cyclical data into rescript-struct will cause an infinite loop. +> 🧠 Despite supporting recursive schema, passing cyclical data into rescript-schema will cause an infinite loop. ## Refinements -**rescript-struct** lets you provide custom validation logic via refinements. It's useful to add checks that's not possible to cover with type system. For instance: checking that a number is an integer or that a string is a valid email address. +**rescript-schema** lets you provide custom validation logic via refinements. It's useful to add checks that's not possible to cover with type system. For instance: checking that a number is an integer or that a string is a valid email address. ### **`refine`** `(S.t<'value>, effectCtx<'value> => 'value => unit) => S.t<'value>` ```rescript -let shortStringStruct = S.string->S.refine(s => value => +let shortStringSchema = S.string->S.refine(s => value => if value->String.length > 255 { s.fail("String can't be more than 255 characters") } @@ -941,15 +941,15 @@ The refine function is applied for both parser and serializer. ## Transforms -**rescript-struct** allows structs to be augmented with transformation logic, letting you transform value during parsing and serializing. This is most commonly used for mapping value to more convenient data structures. +**rescript-schema** allows to augment schema with transformation logic, letting you transform value during parsing and serializing. This is most commonly used for mapping value to more convenient data-structures. ### **`transform`** `(S.t<'input>, S.effectCtx<'output> => S.transformDefinition<'input, 'output>) => S.t<'output>` ```rescript -let intToString = struct => - struct->S.transform(s => { +let intToString = schema => + schema->S.transform(s => { parser: Int.toString, serializer: string => switch string->Int.fromString { @@ -967,7 +967,7 @@ type user = { name: string, } -let userStruct = +let userSchema = S.string ->S.String.uuid ->S.transform(s => { @@ -975,7 +975,7 @@ let userStruct = serializer: user => user.id, }) -await %raw(`"1"`)->S.parseAsyncWith(userStruct) +await %raw(`"1"`)->S.parseAsyncWith(userSchema) // Ok({ // id: "1", // name: "John", @@ -984,19 +984,19 @@ await %raw(`"1"`)->S.parseAsyncWith(userStruct) { id: "1", name: "John", -}->S.serializeWith(userStruct) +}->S.serializeWith(userSchema) // Ok("1") ``` ## Preprocess _Advanced_ -Typically **rescript-struct** operates under a "parse then transform" paradigm. **rescript-struct** validates the input first, then passes it through a chain of transformation functions. +Typically **rescript-schema** operates under a "parse then transform" paradigm. **rescript-schema** validates the input first, then passes it through a chain of transformation functions. -But sometimes you want to apply some transform to the input before parsing happens. Mostly needed when you build sometimes on top of **rescript-struct**. A simplified example from [rescript-envsafe](https://github.com/DZakh/rescript-envsafe): +But sometimes you want to apply some transform to the input before parsing happens. Mostly needed when you build sometimes on top of **rescript-schema**. A simplified example from [rescript-envsafe](https://github.com/DZakh/rescript-envsafe): ```rescript -let prepareEnvStruct = S.preprocess(_, s => { - switch s.struct->S.classify { +let prepareEnvSchema = S.preprocess(_, s => { + switch s.schema->S.classify { | Literal(Boolean(_)) | Bool => { parser: unknown => { @@ -1027,26 +1027,26 @@ let prepareEnvStruct = S.preprocess(_, s => { }) ``` -> 🧠 When using preprocess on Union it will be applied to nested structs separately. +> 🧠 When using preprocess on Union it will be applied to nested schemas separately. -## Functions on struct +## Functions on schema ### **`parseWith`** `(JSON.t, S.t<'value>) => result<'value, S.error>` ```rescript -data->S.parseWith(userStruct) +data->S.parseWith(userSchema) ``` -Given any struct, you can call `parseWith` to check `data` is valid. It returns a result with valid data transformed to expected type or a **rescript-struct** error. +Given any schema, you can call `parseWith` to check `data` is valid. It returns a result with valid data transformed to expected type or a **rescript-schema** error. ### **`parseAnyWith`** `('any, S.t<'value>) => result<'value, S.error>` ```rescript -data->S.parseAnyWith(userStruct) +data->S.parseAnyWith(userSchema) ``` The same as `parseWith`, but the `data` is loosened to the abstract type. @@ -1056,7 +1056,7 @@ The same as `parseWith`, but the `data` is loosened to the abstract type. `(string, S.t<'value>) => result<'value, S.error>` ```rescript -json->S.parseJsonStringWith(userStruct) +json->S.parseJsonStringWith(userSchema) ``` The same as `parseWith`, but applies `JSON.parse` before parsing. @@ -1067,7 +1067,7 @@ The same as `parseWith`, but applies `JSON.parse` before parsing. ```rescript try { - data->S.parseOrRaiseWith(userStruct) + data->S.parseOrRaiseWith(userSchema) } catch { | S.Raised(error) => Exn.raise(error->S.Error.message) } @@ -1081,7 +1081,7 @@ The exception-based version of `parseWith`. ```rescript try { - data->S.parseAnyOrRaiseWith(userStruct) + data->S.parseAnyOrRaiseWith(userSchema) } catch { | S.Raised(error) => Exn.raise(error->S.Error.message) } @@ -1094,7 +1094,7 @@ The exception-based version of `parseAnyWith`. `(JSON.t, S.t<'value>) => promise>` ```rescript -data->S.parseAsyncWith(userStruct) +data->S.parseAsyncWith(userSchema) ``` If you use asynchronous refinements or transforms, you'll need to use `parseAsyncWith`. It will parse all synchronous branches first and then continue with asynchronous refinements and transforms in parallel. @@ -1104,7 +1104,7 @@ If you use asynchronous refinements or transforms, you'll need to use `parseAsyn `(JSON.t, S.t<'value>) => result<(. unit) => promise>, S.error>` ```rescript -data->S.parseAsyncInStepsWith(userStruct) +data->S.parseAsyncInStepsWith(userSchema) ``` After parsing synchronous branches will return a function to run asynchronous refinements and transforms. @@ -1114,29 +1114,29 @@ After parsing synchronous branches will return a function to run asynchronous re `('value, S.t<'value>) => result` ```rescript -user->S.serializeWith(userStruct) +user->S.serializeWith(userSchema) ``` -Serializes value using the transformation logic that is built-in to the struct. It returns a result with a transformed data or a **rescript-struct** error. +Serializes value using the transformation logic that is built-in to the schema. It returns a result with a transformed data or a **rescript-schema** error. -> 🧠 It fails with JSON incompatible structs. Use S.serializeToUnknownWith if you use structs that don't serialize to JSON. +> 🧠 It'll fail with JSON incompatible schema. Use S.serializeToUnknownWith if you have schema which doesn't serialize to JSON. ### **`serializeToUnknownWith`** `('value, S.t<'value>) => result` ```rescript -user->S.serializeToUnknownWith(userStruct) +user->S.serializeToUnknownWith(userSchema) ``` -Similar to the `serializeWith` but returns `unknown` instead of `JSON.t`. Also, it doesn't check the struct on JSON compatibility. +Similar to the `serializeWith` but returns `unknown` instead of `JSON.t`. Also, it doesn't check the schema on JSON compatibility. ### **`serializeToJsonStringWith`** `('value, ~space: int=?, S.t<'value>) => result` ```rescript -user->S.serializeToJsonStringWith(userStruct) +user->S.serializeToJsonStringWith(userSchema) ``` The same as `serializeToUnknownWith`, but applies `JSON.serialize` at the end. @@ -1147,7 +1147,7 @@ The same as `serializeToUnknownWith`, but applies `JSON.serialize` at the end. ```rescript try { - user->S.serializeOrRaiseWith(userStruct) + user->S.serializeOrRaiseWith(userSchema) } catch { | S.Raised(error) => Exn.raise(error->S.Error.message) } @@ -1161,7 +1161,7 @@ The exception-based version of `serializeWith`. ```rescript try { - user->S.serializeToUnknownOrRaiseWith(userStruct) + user->S.serializeToUnknownOrRaiseWith(userSchema) } catch { | S.Raised(error) => Exn.raise(error->S.Error.message) } @@ -1198,22 +1198,22 @@ Used internally for readable error messages. `(S.t<'value>, string) => string` ```rescript -let struct = S.literal({"abc": 123})->S.setName("Abc") +let schema = S.literal({"abc": 123})->S.setName("Abc") -struct->S.name +schema->S.name // `Abc` ``` -You can customise a struct name using `S.setName`. +You can customise a schema name using `S.setName`. ## Error handling -**rescript-struct** returns a result type with error `S.error` containing detailed information about the validation problems. +**rescript-schema** returns a result type with error `S.error` containing detailed information about the validation problems. ```rescript -let struct = S.literal(false) +let schema = S.literal(false) -%raw(`true`)->S.parseWith(struct) +%raw(`true`)->S.parseWith(schema) // Error({ // code: InvalidLiteral({expected: Boolean(false), received: true}), // operation: Parsing, @@ -1221,19 +1221,19 @@ let struct = S.literal(false) // }) ``` -Also you can use the exception-based operations like `parseOrRaiseWith`. In this case the instance of `RescriptStructError` will be thrown with a nice error message. Also, you can use the `S.Raised` exception to catch it in ReScript code. +Also you can use the exception-based operations like `parseOrRaiseWith`. In this case the instance of `RescriptSchemaError` will be thrown with a nice error message. Also, you can use the `S.Raised` exception to catch it in ReScript code. ### **`Error.make`** `(~code: S.errorCode, ~operation: S.operation, ~path: S.Path.t) => S.error` -Creates an instance of `RescriptStructError` error. At the same time it's the `S.Raised` exception. +Creates an instance of `RescriptSchemaError` error. At the same time it's the `S.Raised` exception. ### **`Error.raise`** `S.error => exn` -Throws error. Since internally it's both the `S.Raised` exception and instance of `RescriptStructError`, it'll have a nice error message and can be caught using `S.Raised`. +Throws error. Since internally it's both the `S.Raised` exception and instance of `RescriptSchemaError`, it'll have a nice error message and can be caught using `S.Raised`. ### **`Error.message`** diff --git a/package.json b/package.json index 52903683..1346f747 100644 --- a/package.json +++ b/package.json @@ -1,10 +1,9 @@ { - "name": "rescript-struct", + "name": "rescript-schema", "version": "5.1.1", "description": "The fastest composable parser/serializer for ReScript (and TypeScript)", "keywords": [ "ReScript", - "Struct", "JSON", "Schema", "Typesafe", @@ -16,6 +15,7 @@ "Transform", "Contract", "Mapping", + "Struct", "Jzon", "Zod", "Superstruct", @@ -24,13 +24,13 @@ "Ppx", "Decco" ], - "homepage": "https://github.com/DZakh/rescript-struct#readme", + "homepage": "https://github.com/DZakh/rescript-schema#readme", "bugs": { - "url": "https://github.com/DZakh/rescript-struct/issues" + "url": "https://github.com/DZakh/rescript-schema/issues" }, "repository": { "type": "git", - "url": "git+https://github.com/DZakh/rescript-struct.git" + "url": "git+https://github.com/DZakh/rescript-schema.git" }, "license": "MIT", "author": "Dmitry Zakharov ", @@ -48,7 +48,7 @@ "src/S.bs.js", "src/S.bs.mjs", "src/S.d.ts", - "RescriptStruct.gen.ts", + "RescriptSchema.gen.ts", "bsconfig.json" ], "scripts": { @@ -85,7 +85,7 @@ "c8": "7.12.0", "rescript": "11.0.0-rc.5", "rescript-stdlib-vendorer": "1.0.0", - "rescript-struct": ".", + "rescript-schema": ".", "ts-expect": "1.3.0", "ts-node": "10.9.1", "typescript": "4.9.3", diff --git a/packages/ppx/src/ppx/codecs.ml b/packages/ppx/src/ppx/codecs.ml index 350c711b..c911ff8c 100644 --- a/packages/ppx/src/ppx/codecs.ml +++ b/packages/ppx/src/ppx/codecs.ml @@ -3,13 +3,13 @@ open Parsetree open Ast_helper open Utils -let rec generate_constr_struct_expr { Location.txt = identifier; loc } type_args +let rec generate_constr_schema_expr { Location.txt = identifier; loc } type_args = let open Longident in match (identifier, type_args) with | Lident "string", _ -> [%expr S.string] | Lident "int", _ -> [%expr S.int] - | Lident "int64", _ -> fail loc "Can't generate struct for `int64` type" + | Lident "int64", _ -> fail loc "Can't generate schema for `int64` type" | Lident "float", _ -> [%expr S.float] | Lident "bool", _ -> [%expr S.bool] | Lident "unit", _ -> [%expr S.unit] @@ -18,30 +18,30 @@ let rec generate_constr_struct_expr { Location.txt = identifier; loc } type_args | Ldot (Ldot (Lident "Js", "Json"), "t"), _ | Ldot (Lident "JSON", "t"), _ -> [%expr S.json] | Lident "array", [ item_type ] -> - [%expr S.array [%e generate_struct_expr item_type]] + [%expr S.array [%e generate_schema_expr item_type]] | Lident "list", [ item_type ] -> - [%expr S.list [%e generate_struct_expr item_type]] + [%expr S.list [%e generate_schema_expr item_type]] | Lident "option", [ item_type ] -> - [%expr S.option [%e generate_struct_expr item_type]] + [%expr S.option [%e generate_schema_expr item_type]] | Lident "null", [ item_type ] -> - [%expr S.null [%e generate_struct_expr item_type]] + [%expr S.null [%e generate_schema_expr item_type]] | Ldot (Ldot (Lident "Js", "Dict"), "t"), [ item_type ] | Ldot (Lident "Dict", "t"), [ item_type ] -> - [%expr S.dict [%e generate_struct_expr item_type]] - | Lident s, _ -> make_ident_expr (get_generated_struct_name s) + [%expr S.dict [%e generate_schema_expr item_type]] + | Lident s, _ -> make_ident_expr (get_generated_schema_name s) | Ldot (left, right), _ -> - Exp.ident (mknoloc (Ldot (left, get_generated_struct_name right))) - | Lapply (_, _), _ -> fail loc "Lapply syntax not handled by rescript-struct" + Exp.ident (mknoloc (Ldot (left, get_generated_schema_name right))) + | Lapply (_, _), _ -> fail loc "Lapply syntax not handled by rescript-schema" -and generate_struct_expr { ptyp_desc; ptyp_loc; ptyp_attributes } = - let custom_struct_expr = get_attribute_by_name ptyp_attributes "struct" in - match custom_struct_expr with +and generate_schema_expr { ptyp_desc; ptyp_loc; ptyp_attributes } = + let custom_schema_expr = get_attribute_by_name ptyp_attributes "schema" in + match custom_schema_expr with | Ok None -> ( match ptyp_desc with - | Ptyp_any -> fail ptyp_loc "Can't generate struct for `any` type" + | Ptyp_any -> fail ptyp_loc "Can't generate schema for `any` type" | Ptyp_arrow (_, _, _) -> - fail ptyp_loc "Can't generate struct for function type" - | Ptyp_package _ -> fail ptyp_loc "Can't generate struct for module type" + fail ptyp_loc "Can't generate schema for function type" + | Ptyp_package _ -> fail ptyp_loc "Can't generate schema for module type" | Ptyp_tuple tuple_types -> [%expr S.tuple @@ -53,10 +53,10 @@ and generate_struct_expr { ptyp_desc; ptyp_loc; ptyp_attributes } = [%expr s.item [%e Exp.constant (Const.int idx)] - [%e generate_struct_expr tuple_type]]))]))] - | Ptyp_var s -> make_ident_expr (get_generated_struct_name s) + [%e generate_schema_expr tuple_type]]))]))] + | Ptyp_var s -> make_ident_expr (get_generated_schema_name s) | Ptyp_constr (constr, typeArgs) -> - generate_constr_struct_expr constr typeArgs - | _ -> fail ptyp_loc "This syntax is not yet handled by rescript-struct") + generate_constr_schema_expr constr typeArgs + | _ -> fail ptyp_loc "This syntax is not yet handled by rescript-schema") | Ok (Some attribute) -> get_expr_from_payload attribute | Error s -> fail ptyp_loc s diff --git a/packages/ppx/src/ppx/codecs.mli b/packages/ppx/src/ppx/codecs.mli index 5d1a9968..0537b032 100644 --- a/packages/ppx/src/ppx/codecs.mli +++ b/packages/ppx/src/ppx/codecs.mli @@ -1,3 +1,3 @@ open Parsetree -val generate_struct_expr: core_type ->expression \ No newline at end of file +val generate_schema_expr : core_type -> expression diff --git a/packages/ppx/src/ppx/polyvariants.ml b/packages/ppx/src/ppx/polyvariants.ml index 0ec478fb..6872858d 100644 --- a/packages/ppx/src/ppx/polyvariants.ml +++ b/packages/ppx/src/ppx/polyvariants.ml @@ -11,7 +11,7 @@ let parse_decl { prf_desc } = [%expr S.literal [%e Exp.variant name None]] -let generate_struct_expr row_fields = +let generate_schema_expr row_fields = let union_items = List.map parse_decl row_fields in match union_items with | [ item ] -> item diff --git a/packages/ppx/src/ppx/polyvariants.mli b/packages/ppx/src/ppx/polyvariants.mli index d30f0e98..611178bb 100644 --- a/packages/ppx/src/ppx/polyvariants.mli +++ b/packages/ppx/src/ppx/polyvariants.mli @@ -1,3 +1,3 @@ open Parsetree -val generate_struct_expr : row_field list -> expression +val generate_schema_expr : row_field list -> expression diff --git a/packages/ppx/src/ppx/ppx_struct.ml b/packages/ppx/src/ppx/ppx_struct.ml index 7ce4e420..70f0619a 100644 --- a/packages/ppx/src/ppx/ppx_struct.ml +++ b/packages/ppx/src/ppx/ppx_struct.ml @@ -12,7 +12,7 @@ class mapper = end let signature_mapper = (new mapper)#signature - let structure_mapper = (new mapper)#structure;; -Ppxlib.Driver.register_transformation ~impl:structure_mapper ~intf:signature_mapper "struct" +Ppxlib.Driver.register_transformation ~impl:structure_mapper + ~intf:signature_mapper "schema" diff --git a/packages/ppx/src/ppx/records.ml b/packages/ppx/src/ppx/records.ml index a26d4ab2..40f5e0ff 100644 --- a/packages/ppx/src/ppx/records.ml +++ b/packages/ppx/src/ppx/records.ml @@ -6,7 +6,7 @@ open Utils type field = { name : string; maybe_alias : expression option; - struct_expr : expression; + schema_expr : expression; } let generate_decoder fields = @@ -29,7 +29,7 @@ let generate_decoder fields = ( lid field.name, [%expr s.field [%e original_field_name_expr] - [%e field.struct_expr]] ))) + [%e field.schema_expr]] ))) None]))] let parse_decl { pld_name = { txt }; pld_loc; pld_type; pld_attributes } = @@ -45,14 +45,14 @@ let parse_decl { pld_name = { txt }; pld_loc; pld_type; pld_attributes } = |> List.map (fun attr -> get_attribute_by_name pld_attributes attr) |> List.exists (function Ok (Some _) -> true | _ -> false) in - let struct_expr = Codecs.generate_struct_expr pld_type in - let struct_expr = - if is_optional then [%expr Obj.magic S.option [%e struct_expr]] - else struct_expr + let schema_expr = Codecs.generate_schema_expr pld_type in + let schema_expr = + if is_optional then [%expr Obj.magic S.option [%e schema_expr]] + else schema_expr in - { name = txt; maybe_alias; struct_expr } + { name = txt; maybe_alias; schema_expr } -let generate_struct_expr decls = +let generate_schema_expr decls = let fields = List.map parse_decl decls in generate_decoder fields diff --git a/packages/ppx/src/ppx/records.mli b/packages/ppx/src/ppx/records.mli index e3fe7fd4..858654fe 100644 --- a/packages/ppx/src/ppx/records.mli +++ b/packages/ppx/src/ppx/records.mli @@ -1,3 +1,3 @@ open Parsetree -val generate_struct_expr : label_declaration list -> expression +val generate_schema_expr : label_declaration list -> expression diff --git a/packages/ppx/src/ppx/signature.ml b/packages/ppx/src/ppx/signature.ml index c2766c6b..6b24c99e 100644 --- a/packages/ppx/src/ppx/signature.ml +++ b/packages/ppx/src/ppx/signature.ml @@ -3,13 +3,13 @@ open Parsetree open Ast_helper open Utils -let generate_struct_signature_item ~type_declaration = +let generate_schema_signature_item ~type_declaration = let { ptype_name = { txt = type_name } } = type_declaration in - let struct_name = get_generated_struct_name type_name in + let schema_name = get_generated_schema_name type_name in [%type: [%t Typ.constr (lid type_name) []] S.t] - |> Val.mk (mknoloc struct_name) + |> Val.mk (mknoloc schema_name) |> Sig.value let map_signature_item mapper ({ psig_desc } as signature_item) = @@ -20,12 +20,12 @@ let map_signature_item mapper ({ psig_desc } as signature_item) = |> List.map (fun type_declaration -> match Utils.get_attribute_by_name type_declaration.ptype_attributes - "struct" + "schema" with | Error err -> fail type_declaration.ptype_loc err | Ok None -> [] | Ok (Some _) -> - [ generate_struct_signature_item ~type_declaration ]) + [ generate_schema_signature_item ~type_declaration ]) |> List.concat in mapper#signature_item signature_item :: generated_sig_items diff --git a/packages/ppx/src/ppx/structure.ml b/packages/ppx/src/ppx/structure.ml index 478dc496..290db4bd 100644 --- a/packages/ppx/src/ppx/structure.ml +++ b/packages/ppx/src/ppx/structure.ml @@ -3,13 +3,13 @@ open Parsetree open Ast_helper open Utils -let generate_decls type_name struct_expr = - let struct_name_pat = - Pat.var (mknoloc (get_generated_struct_name type_name)) +let generate_decls type_name schema_expr = + let schema_name_pat = + Pat.var (mknoloc (get_generated_schema_name type_name)) in [ - Vb.mk struct_name_pat - (Exp.constraint_ struct_expr + Vb.mk schema_name_pat + (Exp.constraint_ schema_expr [%type: [%t Typ.constr (lid type_name) []] S.t]); ] @@ -25,22 +25,22 @@ let map_type_decl decl = in match - (get_attribute_by_name ptype_attributes "struct", ptype_manifest, ptype_kind) + (get_attribute_by_name ptype_attributes "schema", ptype_manifest, ptype_kind) with | Ok None, _, _ -> [] | Error err, _, _ -> fail ptype_loc err | Ok _, None, Ptype_abstract -> - fail ptype_loc "Can't generate struct for unspecified type" + fail ptype_loc "Can't generate schema for unspecified type" | Ok _, Some { ptyp_desc = Ptyp_variant (row_fields, _, _) }, Ptype_abstract -> - generate_decls type_name (Polyvariants.generate_struct_expr row_fields) + generate_decls type_name (Polyvariants.generate_schema_expr row_fields) | Ok _, Some manifest, _ -> - generate_decls type_name (Codecs.generate_struct_expr manifest) + generate_decls type_name (Codecs.generate_schema_expr manifest) | Ok _, None, Ptype_variant decls -> - generate_decls type_name (Variants.generate_struct_expr decls) + generate_decls type_name (Variants.generate_schema_expr decls) | Ok _, None, Ptype_record decls -> - generate_decls type_name (Records.generate_struct_expr decls) - | _ -> fail ptype_loc "This type is not handled by rescript-struct" + generate_decls type_name (Records.generate_schema_expr decls) + | _ -> fail ptype_loc "This type is not handled by rescript-schema" let map_structure_item mapper ({ pstr_desc } as structure_item) = match pstr_desc with diff --git a/packages/ppx/src/ppx/utils.ml b/packages/ppx/src/ppx/utils.ml index ed1f0ce5..ef2bcc1d 100644 --- a/packages/ppx/src/ppx/utils.ml +++ b/packages/ppx/src/ppx/utils.ml @@ -28,5 +28,5 @@ let get_expr_from_payload { attr_name = { loc }; attr_payload = payload } = | _ -> fail loc "Expected expression as attribute payload") | _ -> fail loc "Expected expression as attribute payload" -let get_generated_struct_name type_name = - match type_name with "t" -> "struct" | _ -> type_name ^ "Struct" +let get_generated_schema_name type_name = + match type_name with "t" -> "schema" | _ -> type_name ^ "Schema" diff --git a/packages/ppx/src/ppx/variants.ml b/packages/ppx/src/ppx/variants.ml index 0490d4b6..270ebf13 100644 --- a/packages/ppx/src/ppx/variants.ml +++ b/packages/ppx/src/ppx/variants.ml @@ -8,7 +8,7 @@ let parse_decl { pcd_name = { txt = name; loc }; pcd_args } = | Pcstr_tuple [] -> [%expr S.literal [%e Exp.construct (lid name) None]] | _ -> fail loc "Variants with payload not supported yet" -let generate_struct_expr constr_decls = +let generate_schema_expr constr_decls = let union_items = List.map parse_decl constr_decls in match union_items with | [ item ] -> item diff --git a/packages/ppx/src/ppx/variants.mli b/packages/ppx/src/ppx/variants.mli index bc6f84a8..8db06e72 100644 --- a/packages/ppx/src/ppx/variants.mli +++ b/packages/ppx/src/ppx/variants.mli @@ -1,3 +1,3 @@ open Parsetree -val generate_struct_expr : constructor_declaration list -> expression +val generate_schema_expr : constructor_declaration list -> expression diff --git a/packages/ppx/src/ppx_struct.opam b/packages/ppx/src/ppx_struct.opam index d3785a56..c1e03e09 100644 --- a/packages/ppx/src/ppx_struct.opam +++ b/packages/ppx/src/ppx_struct.opam @@ -1,16 +1,16 @@ opam-version: "2.0" name: "ppx_struct" -version: "4.0.0" -synopsis: "Safely parse and serialize with transformation to convenient ReScript data structures" +version: "6.0.0" +synopsis: "PPX for the fastest composable parser/serializer for ReScript (and TypeScript)" description: """ -Safely parse and serialize with transformation to convenient ReScript data structures +PPX for the fastest composable parser/serializer for ReScript (and TypeScript) """ maintainer: "Dmitry Zakharov " authors: "Dmitry Zakharov " license: "MIT" -homepage: "https://github.com/DZakh/rescript-struct" -bug-reports: "https://github.com/DZakh/rescript-struct/issues" -dev-repo: "git+https://github.com/DZakh/rescript-struct.git" +homepage: "https://github.com/DZakh/rescript-schema" +bug-reports: "https://github.com/DZakh/rescript-schema/issues" +dev-repo: "git+https://github.com/DZakh/rescript-schema.git" depends: [ "ocaml" { = "4.12.1"} "dune" { >= "2.7"} diff --git a/packages/prepack/src/Prepack.bs.mjs b/packages/prepack/src/Prepack.bs.mjs index fcc5a7dd..a4e72b15 100644 --- a/packages/prepack/src/Prepack.bs.mjs +++ b/packages/prepack/src/Prepack.bs.mjs @@ -20,14 +20,17 @@ var sourePaths = [ "src", "bsconfig.json", "README.md", - "RescriptStruct.gen.ts" + "RescriptSchema.gen.ts", ]; var jsInputPath = Path.join(artifactsPath, "src/S.js"); function update(json, path, value) { var dict = Core__JSON.Decode.object(json); - var dict$1 = dict !== undefined ? Object.assign({}, Caml_option.valFromOption(dict)) : ({}); + var dict$1 = + dict !== undefined + ? Object.assign({}, Caml_option.valFromOption(dict)) + : {}; if (!path) { return value; } @@ -44,74 +47,70 @@ function update(json, path, value) { if (Fs.existsSync(artifactsPath)) { Fs.rmSync(artifactsPath, { - recursive: true, - force: true - }); + recursive: true, + force: true, + }); } Fs.mkdirSync(artifactsPath); sourePaths.forEach(function (path) { - Fs.cpSync(Path.join(projectPath, path), Path.join(artifactsPath, path), { - recursive: true - }); - }); + Fs.cpSync(Path.join(projectPath, path), Path.join(artifactsPath, path), { + recursive: true, + }); +}); function updateJsonFile(src, path, value) { var packageJsonData = Fs.readFileSync(src, { - encoding: "utf8" - }); + encoding: "utf8", + }); var packageJson = JSON.parse(packageJsonData.toString()); - var updatedPackageJson = JSON.stringify(update(packageJson, Core__List.fromArray(path), value), null, 2); + var updatedPackageJson = JSON.stringify( + update(packageJson, Core__List.fromArray(path), value), + null, + 2 + ); Fs.writeFileSync(src, Buffer.from(updatedPackageJson), { - encoding: "utf8" - }); + encoding: "utf8", + }); } -Execa.execaSync("npm", [ - "run", - "res:build" - ], { - cwd: artifactsPath - }); +Execa.execaSync("npm", ["run", "res:build"], { + cwd: artifactsPath, +}); var bundle = await Rollup.rollup({ - input: jsInputPath, - external: [/S_Core\.bs\.mjs/] - }); + input: jsInputPath, + external: [/S_Core\.bs\.mjs/], +}); var output = [ { file: Path.join(artifactsPath, "dist/S.js"), format: "cjs", exports: "named", - plugins: [PluginReplace({ - values: Object.fromEntries([ - [ - "S_Core.bs.mjs", - "../src/S_Core.bs.js" - ], - [ - "rescript/lib/es6", - "rescript/lib/js" - ] - ]) - })] + plugins: [ + PluginReplace({ + values: Object.fromEntries([ + ["S_Core.bs.mjs", "../src/S_Core.bs.js"], + ["rescript/lib/es6", "rescript/lib/js"], + ]), + }), + ], }, { file: Path.join(artifactsPath, "dist/S.mjs"), format: "es", exports: "named", - plugins: [PluginReplace({ - values: Object.fromEntries([[ - "S_Core.bs.mjs", - "../src/S_Core.bs.mjs" - ]]) - })] - } + plugins: [ + PluginReplace({ + values: Object.fromEntries([["S_Core.bs.mjs", "../src/S_Core.bs.mjs"]]), + }), + ], + }, ]; -for(var idx = 0 ,idx_finish = output.length; idx < idx_finish; ++idx){ +for (var idx = 0, idx_finish = output.length; idx < idx_finish; ++idx) { var outpuOptions = output[idx]; await bundle.write(outpuOptions); } @@ -119,27 +118,23 @@ for(var idx = 0 ,idx_finish = output.length; idx < idx_finish; ++idx){ await bundle.close(); Fs.rmSync(Path.join(artifactsPath, "lib"), { - recursive: true, - force: true - }); + recursive: true, + force: true, +}); -updateJsonFile(Path.join(artifactsPath, "bsconfig.json"), [ - "package-specs", - "module" - ], "commonjs"); +updateJsonFile( + Path.join(artifactsPath, "bsconfig.json"), + ["package-specs", "module"], + "commonjs" +); updateJsonFile(Path.join(artifactsPath, "bsconfig.json"), ["suffix"], ".bs.js"); -Execa.execaSync("npm", [ - "run", - "res:build" - ], { - cwd: artifactsPath - }); +Execa.execaSync("npm", ["run", "res:build"], { + cwd: artifactsPath, +}); updateJsonFile(Path.join(artifactsPath, "package.json"), ["type"], "commonjs"); -export { - -} +export {}; /* artifactsPath Not a pure module */ diff --git a/packages/prepack/src/Prepack.res b/packages/prepack/src/Prepack.res index e7f239e4..ff3542ff 100644 --- a/packages/prepack/src/Prepack.res +++ b/packages/prepack/src/Prepack.res @@ -6,7 +6,7 @@ let sourePaths = [ "src", "bsconfig.json", "README.md", - "RescriptStruct.gen.ts", + "RescriptSchema.gen.ts", ] let jsInputPath = NodeJs.Path.join2(artifactsPath, "src/S.js") @@ -192,4 +192,4 @@ updateJsonFile( ~value=JSON.Encode.string("commonjs"), ) -// TODO: Generate RescriptStruct.gen.ts +// TODO: Generate RescriptSchema.gen.ts diff --git a/packages/tests/bsconfig.json b/packages/tests/bsconfig.json index 88c49ccf..c80e22b3 100644 --- a/packages/tests/bsconfig.json +++ b/packages/tests/bsconfig.json @@ -12,10 +12,10 @@ "in-source": true }, "suffix": ".bs.mjs", - "bs-dependencies": ["rescript-struct"], + "bs-dependencies": ["rescript-schema"], "bs-dev-dependencies": ["@dzakh/rescript-core", "@dzakh/rescript-ava"], "ppx-flags": ["../ppx/ppx"], - "bsc-flags": ["-open RescriptStruct"], + "bsc-flags": ["-open RescriptSchema"], "warnings": { "error": true, "number": "-48-44" diff --git a/packages/tests/src/benchmark/Benchmark.bs.mjs b/packages/tests/src/benchmark/Benchmark.bs.mjs index 4ded6313..7683767e 100644 --- a/packages/tests/src/benchmark/Benchmark.bs.mjs +++ b/packages/tests/src/benchmark/Benchmark.bs.mjs @@ -1,7 +1,7 @@ // Generated by ReScript, PLEASE EDIT WITH CARE import * as Benchmark from "benchmark"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; function addWithPrepare(suite, name, fn) { return suite.add(name, fn()); @@ -30,40 +30,40 @@ function makeTestObject() { })); } -function makeAdvancedObjectStruct() { - return S$RescriptStruct.object(function (s) { +function makeAdvancedObjectSchema() { + return S$RescriptSchema.object(function (s) { return { - number: s.f("number", S$RescriptStruct.$$float), - negNumber: s.f("negNumber", S$RescriptStruct.$$float), - maxNumber: s.f("maxNumber", S$RescriptStruct.$$float), - string: s.f("string", S$RescriptStruct.string), - longString: s.f("longString", S$RescriptStruct.string), - boolean: s.f("boolean", S$RescriptStruct.bool), - deeplyNested: s.f("deeplyNested", S$RescriptStruct.object(function (s) { + number: s.f("number", S$RescriptSchema.$$float), + negNumber: s.f("negNumber", S$RescriptSchema.$$float), + maxNumber: s.f("maxNumber", S$RescriptSchema.$$float), + string: s.f("string", S$RescriptSchema.string), + longString: s.f("longString", S$RescriptSchema.string), + boolean: s.f("boolean", S$RescriptSchema.bool), + deeplyNested: s.f("deeplyNested", S$RescriptSchema.object(function (s) { return { - foo: s.f("foo", S$RescriptStruct.string), - num: s.f("num", S$RescriptStruct.$$float), - bool: s.f("bool", S$RescriptStruct.bool) + foo: s.f("foo", S$RescriptSchema.string), + num: s.f("num", S$RescriptSchema.$$float), + bool: s.f("bool", S$RescriptSchema.bool) }; })) }; }); } -function makeAdvancedStrictObjectStruct() { - return S$RescriptStruct.$$Object.strict(S$RescriptStruct.object(function (s) { +function makeAdvancedStrictObjectSchema() { + return S$RescriptSchema.$$Object.strict(S$RescriptSchema.object(function (s) { return { - number: s.f("number", S$RescriptStruct.$$float), - negNumber: s.f("negNumber", S$RescriptStruct.$$float), - maxNumber: s.f("maxNumber", S$RescriptStruct.$$float), - string: s.f("string", S$RescriptStruct.string), - longString: s.f("longString", S$RescriptStruct.string), - boolean: s.f("boolean", S$RescriptStruct.bool), - deeplyNested: s.f("deeplyNested", S$RescriptStruct.$$Object.strict(S$RescriptStruct.object(function (s) { + number: s.f("number", S$RescriptSchema.$$float), + negNumber: s.f("negNumber", S$RescriptSchema.$$float), + maxNumber: s.f("maxNumber", S$RescriptSchema.$$float), + string: s.f("string", S$RescriptSchema.string), + longString: s.f("longString", S$RescriptSchema.string), + boolean: s.f("boolean", S$RescriptSchema.bool), + deeplyNested: s.f("deeplyNested", S$RescriptSchema.$$Object.strict(S$RescriptSchema.object(function (s) { return { - foo: s.f("foo", S$RescriptStruct.string), - num: s.f("num", S$RescriptStruct.$$float), - bool: s.f("bool", S$RescriptStruct.bool) + foo: s.f("foo", S$RescriptSchema.string), + num: s.f("num", S$RescriptSchema.$$float), + bool: s.f("bool", S$RescriptSchema.bool) }; }))) }; @@ -74,77 +74,77 @@ var data = makeTestObject(); console.time("init"); -var struct = makeAdvancedObjectStruct(); +var schema = makeAdvancedObjectSchema(); console.timeEnd("init"); console.time("p: 1"); -S$RescriptStruct.parseAnyWith(data, struct); +S$RescriptSchema.parseAnyWith(data, schema); console.timeEnd("p: 1"); console.time("p: 2"); -S$RescriptStruct.parseAnyWith(data, struct); +S$RescriptSchema.parseAnyWith(data, schema); console.timeEnd("p: 2"); console.time("p: 3"); -S$RescriptStruct.parseAnyWith(data, struct); +S$RescriptSchema.parseAnyWith(data, schema); console.timeEnd("p: 3"); console.time("s: 1"); -S$RescriptStruct.serializeWith(data, struct); +S$RescriptSchema.serializeWith(data, schema); console.timeEnd("s: 1"); console.time("s: 2"); -S$RescriptStruct.serializeWith(data, struct); +S$RescriptSchema.serializeWith(data, schema); console.timeEnd("s: 2"); console.time("s: 3"); -S$RescriptStruct.serializeWith(data, struct); +S$RescriptSchema.serializeWith(data, schema); console.timeEnd("s: 3"); run(addWithPrepare(addWithPrepare(addWithPrepare(addWithPrepare(addWithPrepare(addWithPrepare(new (Benchmark.default.Suite)(), "Parse string", (function () { return function () { - return S$RescriptStruct.parseAnyOrRaiseWith("Hello world!", S$RescriptStruct.string); + return S$RescriptSchema.parseAnyOrRaiseWith("Hello world!", S$RescriptSchema.string); }; })), "Serialize string", (function () { return function () { - return S$RescriptStruct.serializeOrRaiseWith("Hello world!", S$RescriptStruct.string); + return S$RescriptSchema.serializeOrRaiseWith("Hello world!", S$RescriptSchema.string); }; - })).add("Advanced object struct factory", makeAdvancedObjectStruct), "Parse advanced object", (function () { - var struct = makeAdvancedObjectStruct(); + })).add("Advanced object schema factory", makeAdvancedObjectSchema), "Parse advanced object", (function () { + var schema = makeAdvancedObjectSchema(); var data = makeTestObject(); return function () { - return S$RescriptStruct.parseAnyOrRaiseWith(data, struct); + return S$RescriptSchema.parseAnyOrRaiseWith(data, schema); }; })), "Create and parse advanced object", (function () { var data = makeTestObject(); return function () { - var struct = makeAdvancedObjectStruct(); - return S$RescriptStruct.parseAnyOrRaiseWith(data, struct); + var schema = makeAdvancedObjectSchema(); + return S$RescriptSchema.parseAnyOrRaiseWith(data, schema); }; })), "Parse advanced strict object", (function () { - var struct = makeAdvancedStrictObjectStruct(); + var schema = makeAdvancedStrictObjectSchema(); var data = makeTestObject(); return function () { - return S$RescriptStruct.parseAnyOrRaiseWith(data, struct); + return S$RescriptSchema.parseAnyOrRaiseWith(data, schema); }; })), "Serialize advanced object", (function () { - var struct = makeAdvancedObjectStruct(); + var schema = makeAdvancedObjectSchema(); var data = makeTestObject(); return function () { - return S$RescriptStruct.serializeOrRaiseWith(data, struct); + return S$RescriptSchema.serializeOrRaiseWith(data, schema); }; }))); diff --git a/packages/tests/src/benchmark/Benchmark.res b/packages/tests/src/benchmark/Benchmark.res index 4f142dc4..9a08de90 100644 --- a/packages/tests/src/benchmark/Benchmark.res +++ b/packages/tests/src/benchmark/Benchmark.res @@ -53,7 +53,7 @@ let makeTestObject = () => { })`) } -let makeAdvancedObjectStruct = () => { +let makeAdvancedObjectSchema = () => { S.object(s => { "number": s.field("number", S.float), @@ -76,7 +76,7 @@ let makeAdvancedObjectStruct = () => { ) } -let makeAdvancedStrictObjectStruct = () => { +let makeAdvancedStrictObjectSchema = () => { S.object(s => { "number": s.field("number", S.float), @@ -101,69 +101,69 @@ let makeAdvancedStrictObjectStruct = () => { let data = makeTestObject() Console.time("init") -let struct = makeAdvancedObjectStruct() +let schema = makeAdvancedObjectSchema() Console.timeEnd("init") Console.time("p: 1") -data->S.parseAnyWith(struct)->ignore +data->S.parseAnyWith(schema)->ignore Console.timeEnd("p: 1") Console.time("p: 2") -data->S.parseAnyWith(struct)->ignore +data->S.parseAnyWith(schema)->ignore Console.timeEnd("p: 2") Console.time("p: 3") -data->S.parseAnyWith(struct)->ignore +data->S.parseAnyWith(schema)->ignore Console.timeEnd("p: 3") Console.time("s: 1") -data->S.serializeWith(struct)->ignore +data->S.serializeWith(schema)->ignore Console.timeEnd("s: 1") Console.time("s: 2") -data->S.serializeWith(struct)->ignore +data->S.serializeWith(schema)->ignore Console.timeEnd("s: 2") Console.time("s: 3") -data->S.serializeWith(struct)->ignore +data->S.serializeWith(schema)->ignore Console.timeEnd("s: 3") Suite.make() ->Suite.addWithPrepare("Parse string", () => { - let struct = S.string + let schema = S.string let data = "Hello world!" () => { - data->S.parseAnyOrRaiseWith(struct) + data->S.parseAnyOrRaiseWith(schema) } }) ->Suite.addWithPrepare("Serialize string", () => { - let struct = S.string + let schema = S.string let data = "Hello world!" () => { - data->S.serializeOrRaiseWith(struct) + data->S.serializeOrRaiseWith(schema) } }) -->Suite.add("Advanced object struct factory", makeAdvancedObjectStruct) +->Suite.add("Advanced object schema factory", makeAdvancedObjectSchema) ->Suite.addWithPrepare("Parse advanced object", () => { - let struct = makeAdvancedObjectStruct() + let schema = makeAdvancedObjectSchema() let data = makeTestObject() () => { - data->S.parseAnyOrRaiseWith(struct) + data->S.parseAnyOrRaiseWith(schema) } }) ->Suite.addWithPrepare("Create and parse advanced object", () => { let data = makeTestObject() () => { - let struct = makeAdvancedObjectStruct() - data->S.parseAnyOrRaiseWith(struct) + let schema = makeAdvancedObjectSchema() + data->S.parseAnyOrRaiseWith(schema) } }) ->Suite.addWithPrepare("Parse advanced strict object", () => { - let struct = makeAdvancedStrictObjectStruct() + let schema = makeAdvancedStrictObjectSchema() let data = makeTestObject() () => { - data->S.parseAnyOrRaiseWith(struct) + data->S.parseAnyOrRaiseWith(schema) } }) ->Suite.addWithPrepare("Serialize advanced object", () => { - let struct = makeAdvancedObjectStruct() + let schema = makeAdvancedObjectSchema() let data = makeTestObject() () => { - data->S.serializeOrRaiseWith(struct) + data->S.serializeOrRaiseWith(schema) } }) ->Suite.run diff --git a/packages/tests/src/benchmark/comparison.js b/packages/tests/src/benchmark/comparison.js index 922b897b..eb7608a2 100644 --- a/packages/tests/src/benchmark/comparison.js +++ b/packages/tests/src/benchmark/comparison.js @@ -1,7 +1,7 @@ import B from "benchmark"; import { z } from "zod"; import * as V from "valibot"; -import * as S from "rescript-struct/src/S.js"; +import * as S from "rescript-schema/src/S.js"; const data = Object.freeze({ number: 1, @@ -46,7 +46,7 @@ const valibotSchema = V.object({ }), }); -const struct = S.object({ +const schema = S.object({ number: S.number, negNumber: S.number, maxNumber: S.number, @@ -130,7 +130,7 @@ new B.Suite() }); return V.parse(valibotSchema, data); }) - .add("rescript-struct (create)", () => { + .add("rescript-schema (create)", () => { return S.object({ number: S.number, negNumber: S.number, @@ -145,11 +145,11 @@ new B.Suite() }), }); }) - .add("rescript-struct (parse)", () => { - return S.parseOrThrow(struct, data); + .add("rescript-schema (parse)", () => { + return S.parseOrThrow(schema, data); }) - .add("rescript-struct (create + parse)", () => { - const struct = S.object({ + .add("rescript-schema (create + parse)", () => { + const schema = S.object({ number: S.number, negNumber: S.number, maxNumber: S.number, @@ -162,7 +162,7 @@ new B.Suite() bool: S.boolean, }), }); - return S.parseOrThrow(struct, data); + return S.parseOrThrow(schema, data); }) .on("cycle", (event) => { console.log(String(event.target)); diff --git a/packages/tests/src/core/Example_test.res b/packages/tests/src/core/Example_test.res index 4f202dfb..53754f2e 100644 --- a/packages/tests/src/core/Example_test.res +++ b/packages/tests/src/core/Example_test.res @@ -16,7 +16,7 @@ type film = { deprecatedAgeRestriction: option, } -let filmStruct = S.object(s => { +let filmSchema = S.object(s => { id: s.field("Id", S.float), title: s.field("Title", S.string), tags: s.fieldOr("Tags", S.array(S.string), []), @@ -34,7 +34,7 @@ let filmStruct = S.object(s => { test("Example", t => { t->Assert.deepEqual( - %raw(`{"Id": 1, "Title": "My first film", "Rating": "R", "Age": 17}`)->S.parseWith(filmStruct), + %raw(`{"Id": 1, "Title": "My first film", "Rating": "R", "Age": 17}`)->S.parseWith(filmSchema), Ok({ id: 1., title: "My first film", @@ -51,7 +51,7 @@ test("Example", t => { title: "Sad & sed", rating: ParentalStronglyCautioned, deprecatedAgeRestriction: None, - }->S.serializeWith(filmStruct), + }->S.serializeWith(filmSchema), Ok( %raw(`{ "Id": 2, @@ -67,7 +67,7 @@ test("Example", t => { test("Compiled parse code snapshot", t => { t->U.assertCompiledCode( - ~struct=filmStruct, + ~schema=filmSchema, ~op=#parse, `i=>{let v0,v1,v2,v3,v8,v9,v14,v15;if(!i||i.constructor!==Object){e[15](i)}v0=i["Id"];if(typeof v0!=="number"||Number.isNaN(v0)){e[0](v0)}v1=i["Title"];if(typeof v1!=="string"){e[1](v1)}v2=i["Tags"];if(v2!==void 0&&(!Array.isArray(v2))){e[2](v2)}if(v2!==void 0){let v5;v5=[];for(let v4=0;v42147483647||v14<-2147483648||v14%1!==0)){e[14](v14)}if(v14!==void 0){v15=v14}else{v15=void 0}return {"id":v0,"title":v1,"tags":v3===void 0?e[4]:v3,"rating":v9,"deprecatedAgeRestriction":v15,}}`, ) @@ -75,7 +75,7 @@ test("Compiled parse code snapshot", t => { test("Compiled serialize code snapshot", t => { t->U.assertCompiledCode( - ~struct=filmStruct, + ~schema=filmSchema, ~op=#serialize, `i=>{let v0,v1,v2,v3,v8,v9;v0=i["tags"];if(v0!==void 0){v1=e[0](v0)}else{v1=void 0}v2=i["rating"];try{v2===e[1]||e[2](v2);v3=v2}catch(v4){if(v4&&v4.s===s){try{v2===e[3]||e[4](v2);v3=v2}catch(v5){if(v5&&v5.s===s){try{v2===e[5]||e[6](v2);v3=v2}catch(v6){if(v6&&v6.s===s){try{v2===e[7]||e[8](v2);v3=v2}catch(v7){if(v7&&v7.s===s){e[9]([v4,v5,v6,v7,])}else{throw v7}}}else{throw v6}}}else{throw v5}}}else{throw v4}}v8=i["deprecatedAgeRestriction"];if(v8!==void 0){v9=e[10](v8)}else{v9=void 0}return {"Id":i["id"],"Title":i["title"],"Tags":v1,"Rating":v3,"Age":v9,}}`, ) diff --git a/packages/tests/src/core/S_Array_length_test.res b/packages/tests/src/core/S_Array_length_test.res index e756d749..ce8a7e60 100644 --- a/packages/tests/src/core/S_Array_length_test.res +++ b/packages/tests/src/core/S_Array_length_test.res @@ -1,16 +1,16 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.array(S.int)->S.Array.length(1) + let schema = S.array(S.int)->S.Array.length(1) - t->Assert.deepEqual([1]->S.parseAnyWith(struct), Ok([1]), ()) + t->Assert.deepEqual([1]->S.parseAnyWith(schema), Ok([1]), ()) }) test("Fails to parse invalid data", t => { - let struct = S.array(S.int)->S.Array.length(1) + let schema = S.array(S.int)->S.Array.length(1) t->Assert.deepEqual( - []->S.parseAnyWith(struct), + []->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Array must be exactly 1 items long"), @@ -21,7 +21,7 @@ test("Fails to parse invalid data", t => { (), ) t->Assert.deepEqual( - [1, 2, 3, 4]->S.parseAnyWith(struct), + [1, 2, 3, 4]->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Array must be exactly 1 items long"), @@ -34,16 +34,16 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.array(S.int)->S.Array.length(1) + let schema = S.array(S.int)->S.Array.length(1) - t->Assert.deepEqual([1]->S.serializeToUnknownWith(struct), Ok(%raw(`[1]`)), ()) + t->Assert.deepEqual([1]->S.serializeToUnknownWith(schema), Ok(%raw(`[1]`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.array(S.int)->S.Array.length(1) + let schema = S.array(S.int)->S.Array.length(1) t->Assert.deepEqual( - []->S.serializeToUnknownWith(struct), + []->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Array must be exactly 1 items long"), @@ -54,7 +54,7 @@ test("Fails to serialize invalid value", t => { (), ) t->Assert.deepEqual( - [1, 2, 3, 4]->S.serializeToUnknownWith(struct), + [1, 2, 3, 4]->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Array must be exactly 1 items long"), @@ -67,20 +67,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.array(S.int)->S.Array.length(~message="Custom", 1) + let schema = S.array(S.int)->S.Array.length(~message="Custom", 1) t->Assert.deepEqual( - []->S.parseAnyWith(struct), + []->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.array(S.int)->S.Array.length(1) + let schema = S.array(S.int)->S.Array.length(1) t->Assert.deepEqual( - struct->S.Array.refinements, + schema->S.Array.refinements, [{kind: Length({length: 1}), message: "Array must be exactly 1 items long"}], (), ) diff --git a/packages/tests/src/core/S_Array_max_test.res b/packages/tests/src/core/S_Array_max_test.res index 1cab0710..603c34c7 100644 --- a/packages/tests/src/core/S_Array_max_test.res +++ b/packages/tests/src/core/S_Array_max_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.array(S.int)->S.Array.max(1) + let schema = S.array(S.int)->S.Array.max(1) - t->Assert.deepEqual([1]->S.parseAnyWith(struct), Ok([1]), ()) - t->Assert.deepEqual([]->S.parseAnyWith(struct), Ok([]), ()) + t->Assert.deepEqual([1]->S.parseAnyWith(schema), Ok([1]), ()) + t->Assert.deepEqual([]->S.parseAnyWith(schema), Ok([]), ()) }) test("Fails to parse invalid data", t => { - let struct = S.array(S.int)->S.Array.max(1) + let schema = S.array(S.int)->S.Array.max(1) t->Assert.deepEqual( - [1, 2, 3, 4]->S.parseAnyWith(struct), + [1, 2, 3, 4]->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Array must be 1 or fewer items long"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.array(S.int)->S.Array.max(1) + let schema = S.array(S.int)->S.Array.max(1) - t->Assert.deepEqual([1]->S.serializeToUnknownWith(struct), Ok(%raw(`[1]`)), ()) - t->Assert.deepEqual([]->S.serializeToUnknownWith(struct), Ok(%raw(`[]`)), ()) + t->Assert.deepEqual([1]->S.serializeToUnknownWith(schema), Ok(%raw(`[1]`)), ()) + t->Assert.deepEqual([]->S.serializeToUnknownWith(schema), Ok(%raw(`[]`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.array(S.int)->S.Array.max(1) + let schema = S.array(S.int)->S.Array.max(1) t->Assert.deepEqual( - [1, 2, 3, 4]->S.serializeToUnknownWith(struct), + [1, 2, 3, 4]->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Array must be 1 or fewer items long"), @@ -47,20 +47,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.array(S.int)->S.Array.max(~message="Custom", 1) + let schema = S.array(S.int)->S.Array.max(~message="Custom", 1) t->Assert.deepEqual( - [1, 2]->S.parseAnyWith(struct), + [1, 2]->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.array(S.int)->S.Array.max(1) + let schema = S.array(S.int)->S.Array.max(1) t->Assert.deepEqual( - struct->S.Array.refinements, + schema->S.Array.refinements, [{kind: Max({length: 1}), message: "Array must be 1 or fewer items long"}], (), ) diff --git a/packages/tests/src/core/S_Array_min_test.res b/packages/tests/src/core/S_Array_min_test.res index 7075524a..4d989cc7 100644 --- a/packages/tests/src/core/S_Array_min_test.res +++ b/packages/tests/src/core/S_Array_min_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.array(S.int)->S.Array.min(1) + let schema = S.array(S.int)->S.Array.min(1) - t->Assert.deepEqual([1]->S.parseAnyWith(struct), Ok([1]), ()) - t->Assert.deepEqual([1, 2, 3, 4]->S.parseAnyWith(struct), Ok([1, 2, 3, 4]), ()) + t->Assert.deepEqual([1]->S.parseAnyWith(schema), Ok([1]), ()) + t->Assert.deepEqual([1, 2, 3, 4]->S.parseAnyWith(schema), Ok([1, 2, 3, 4]), ()) }) test("Fails to parse invalid data", t => { - let struct = S.array(S.int)->S.Array.min(1) + let schema = S.array(S.int)->S.Array.min(1) t->Assert.deepEqual( - []->S.parseAnyWith(struct), + []->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Array must be 1 or more items long"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.array(S.int)->S.Array.min(1) + let schema = S.array(S.int)->S.Array.min(1) - t->Assert.deepEqual([1]->S.serializeToUnknownWith(struct), Ok(%raw(`[1]`)), ()) - t->Assert.deepEqual([1, 2, 3, 4]->S.serializeToUnknownWith(struct), Ok(%raw(`[1,2,3,4]`)), ()) + t->Assert.deepEqual([1]->S.serializeToUnknownWith(schema), Ok(%raw(`[1]`)), ()) + t->Assert.deepEqual([1, 2, 3, 4]->S.serializeToUnknownWith(schema), Ok(%raw(`[1,2,3,4]`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.array(S.int)->S.Array.min(1) + let schema = S.array(S.int)->S.Array.min(1) t->Assert.deepEqual( - []->S.serializeToUnknownWith(struct), + []->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Array must be 1 or more items long"), @@ -47,20 +47,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.array(S.int)->S.Array.min(~message="Custom", 1) + let schema = S.array(S.int)->S.Array.min(~message="Custom", 1) t->Assert.deepEqual( - []->S.parseAnyWith(struct), + []->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.array(S.int)->S.Array.min(1) + let schema = S.array(S.int)->S.Array.min(1) t->Assert.deepEqual( - struct->S.Array.refinements, + schema->S.Array.refinements, [{kind: Min({length: 1}), message: "Array must be 1 or more items long"}], (), ) diff --git a/packages/tests/src/core/S_Error_message_test.res b/packages/tests/src/core/S_Error_message_test.res index f412f15b..03eea7c4 100644 --- a/packages/tests/src/core/S_Error_message_test.res +++ b/packages/tests/src/core/S_Error_message_test.res @@ -211,7 +211,7 @@ test("InvalidJsonStruct error", t => { operation: Serializing, path: S.Path.empty, })->S.Error.message, - `Failed serializing at root. Reason: The struct Option(Literal(true)) is not compatible with JSON`, + `Failed serializing at root. Reason: The schema Option(Literal(true)) is not compatible with JSON`, (), ) }) diff --git a/packages/tests/src/core/S_Error_raise_test.res b/packages/tests/src/core/S_Error_raise_test.res index 966c8191..2befb80a 100644 --- a/packages/tests/src/core/S_Error_raise_test.res +++ b/packages/tests/src/core/S_Error_raise_test.res @@ -1,7 +1,7 @@ open Ava test( - "Raised error is instance of RescriptStructError and displayed with a nice error message when not caught", + "Raised error is instance of RescriptSchemaError and displayed with a nice error message when not caught", t => { t->Assert.throws( () => { diff --git a/packages/tests/src/core/S_Float_max_test.res b/packages/tests/src/core/S_Float_max_test.res index 4266a6e8..45d53518 100644 --- a/packages/tests/src/core/S_Float_max_test.res +++ b/packages/tests/src/core/S_Float_max_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.float->S.Float.max(1.) + let schema = S.float->S.Float.max(1.) - t->Assert.deepEqual(1->S.parseAnyWith(struct), Ok(1.), ()) - t->Assert.deepEqual(-1->S.parseAnyWith(struct), Ok(-1.), ()) + t->Assert.deepEqual(1->S.parseAnyWith(schema), Ok(1.), ()) + t->Assert.deepEqual(-1->S.parseAnyWith(schema), Ok(-1.), ()) }) test("Fails to parse invalid data", t => { - let struct = S.float->S.Float.max(1.) + let schema = S.float->S.Float.max(1.) t->Assert.deepEqual( - 1234->S.parseAnyWith(struct), + 1234->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Number must be lower than or equal to 1"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.float->S.Float.max(1.) + let schema = S.float->S.Float.max(1.) - t->Assert.deepEqual(1.->S.serializeToUnknownWith(struct), Ok(%raw(`1`)), ()) - t->Assert.deepEqual(-1.->S.serializeToUnknownWith(struct), Ok(%raw(`-1`)), ()) + t->Assert.deepEqual(1.->S.serializeToUnknownWith(schema), Ok(%raw(`1`)), ()) + t->Assert.deepEqual(-1.->S.serializeToUnknownWith(schema), Ok(%raw(`-1`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.float->S.Float.max(1.) + let schema = S.float->S.Float.max(1.) t->Assert.deepEqual( - 1234.->S.serializeToUnknownWith(struct), + 1234.->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Number must be lower than or equal to 1"), @@ -47,30 +47,30 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.float->S.Float.max(~message="Custom", 1.) + let schema = S.float->S.Float.max(~message="Custom", 1.) t->Assert.deepEqual( - 12.->S.parseAnyWith(struct), + 12.->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.float->S.Float.max(1.) + let schema = S.float->S.Float.max(1.) t->Assert.deepEqual( - struct->S.Float.refinements, + schema->S.Float.refinements, [{kind: Max({value: 1.}), message: "Number must be lower than or equal to 1"}], (), ) }) test("Compiled parse code snapshot", t => { - let struct = S.float->S.Float.max(~message="Custom", 1.) + let schema = S.float->S.Float.max(~message="Custom", 1.) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{if(typeof i!=="number"||Number.isNaN(i)){e[2](i)}if(i>e[0]){e[1]()}return i}`, ) diff --git a/packages/tests/src/core/S_Float_min_test.res b/packages/tests/src/core/S_Float_min_test.res index a8b4adbe..26308e04 100644 --- a/packages/tests/src/core/S_Float_min_test.res +++ b/packages/tests/src/core/S_Float_min_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.float->S.Float.min(1.) + let schema = S.float->S.Float.min(1.) - t->Assert.deepEqual(1.->S.parseAnyWith(struct), Ok(1.), ()) - t->Assert.deepEqual(1234.->S.parseAnyWith(struct), Ok(1234.), ()) + t->Assert.deepEqual(1.->S.parseAnyWith(schema), Ok(1.), ()) + t->Assert.deepEqual(1234.->S.parseAnyWith(schema), Ok(1234.), ()) }) test("Fails to parse invalid data", t => { - let struct = S.float->S.Float.min(1.) + let schema = S.float->S.Float.min(1.) t->Assert.deepEqual( - 0->S.parseAnyWith(struct), + 0->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Number must be greater than or equal to 1"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.float->S.Float.min(1.) + let schema = S.float->S.Float.min(1.) - t->Assert.deepEqual(1.->S.serializeToUnknownWith(struct), Ok(%raw(`1`)), ()) - t->Assert.deepEqual(1234.->S.serializeToUnknownWith(struct), Ok(%raw(`1234`)), ()) + t->Assert.deepEqual(1.->S.serializeToUnknownWith(schema), Ok(%raw(`1`)), ()) + t->Assert.deepEqual(1234.->S.serializeToUnknownWith(schema), Ok(%raw(`1234`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.float->S.Float.min(1.) + let schema = S.float->S.Float.min(1.) t->Assert.deepEqual( - 0.->S.serializeToUnknownWith(struct), + 0.->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Number must be greater than or equal to 1"), @@ -47,20 +47,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.float->S.Float.min(~message="Custom", 1.) + let schema = S.float->S.Float.min(~message="Custom", 1.) t->Assert.deepEqual( - 0.->S.parseAnyWith(struct), + 0.->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.float->S.Float.min(1.) + let schema = S.float->S.Float.min(1.) t->Assert.deepEqual( - struct->S.Float.refinements, + schema->S.Float.refinements, [{kind: Min({value: 1.}), message: "Number must be greater than or equal to 1"}], (), ) diff --git a/packages/tests/src/core/S_Int_max_test.res b/packages/tests/src/core/S_Int_max_test.res index 7036481e..04fb8759 100644 --- a/packages/tests/src/core/S_Int_max_test.res +++ b/packages/tests/src/core/S_Int_max_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.int->S.Int.max(1) + let schema = S.int->S.Int.max(1) - t->Assert.deepEqual(1->S.parseAnyWith(struct), Ok(1), ()) - t->Assert.deepEqual(-1->S.parseAnyWith(struct), Ok(-1), ()) + t->Assert.deepEqual(1->S.parseAnyWith(schema), Ok(1), ()) + t->Assert.deepEqual(-1->S.parseAnyWith(schema), Ok(-1), ()) }) test("Fails to parse invalid data", t => { - let struct = S.int->S.Int.max(1) + let schema = S.int->S.Int.max(1) t->Assert.deepEqual( - 1234->S.parseAnyWith(struct), + 1234->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Number must be lower than or equal to 1"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.int->S.Int.max(1) + let schema = S.int->S.Int.max(1) - t->Assert.deepEqual(1->S.serializeToUnknownWith(struct), Ok(%raw(`1`)), ()) - t->Assert.deepEqual(-1->S.serializeToUnknownWith(struct), Ok(%raw(`-1`)), ()) + t->Assert.deepEqual(1->S.serializeToUnknownWith(schema), Ok(%raw(`1`)), ()) + t->Assert.deepEqual(-1->S.serializeToUnknownWith(schema), Ok(%raw(`-1`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.int->S.Int.max(1) + let schema = S.int->S.Int.max(1) t->Assert.deepEqual( - 1234->S.serializeToUnknownWith(struct), + 1234->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Number must be lower than or equal to 1"), @@ -47,20 +47,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.int->S.Int.max(~message="Custom", 1) + let schema = S.int->S.Int.max(~message="Custom", 1) t->Assert.deepEqual( - 12->S.parseAnyWith(struct), + 12->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.int->S.Int.max(1) + let schema = S.int->S.Int.max(1) t->Assert.deepEqual( - struct->S.Int.refinements, + schema->S.Int.refinements, [{kind: Max({value: 1}), message: "Number must be lower than or equal to 1"}], (), ) diff --git a/packages/tests/src/core/S_Int_min_test.res b/packages/tests/src/core/S_Int_min_test.res index d62eb3be..8a482ca3 100644 --- a/packages/tests/src/core/S_Int_min_test.res +++ b/packages/tests/src/core/S_Int_min_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.int->S.Int.min(1) + let schema = S.int->S.Int.min(1) - t->Assert.deepEqual(1->S.parseAnyWith(struct), Ok(1), ()) - t->Assert.deepEqual(1234->S.parseAnyWith(struct), Ok(1234), ()) + t->Assert.deepEqual(1->S.parseAnyWith(schema), Ok(1), ()) + t->Assert.deepEqual(1234->S.parseAnyWith(schema), Ok(1234), ()) }) test("Fails to parse invalid data", t => { - let struct = S.int->S.Int.min(1) + let schema = S.int->S.Int.min(1) t->Assert.deepEqual( - 0->S.parseAnyWith(struct), + 0->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Number must be greater than or equal to 1"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.int->S.Int.min(1) + let schema = S.int->S.Int.min(1) - t->Assert.deepEqual(1->S.serializeToUnknownWith(struct), Ok(%raw(`1`)), ()) - t->Assert.deepEqual(1234->S.serializeToUnknownWith(struct), Ok(%raw(`1234`)), ()) + t->Assert.deepEqual(1->S.serializeToUnknownWith(schema), Ok(%raw(`1`)), ()) + t->Assert.deepEqual(1234->S.serializeToUnknownWith(schema), Ok(%raw(`1234`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.int->S.Int.min(1) + let schema = S.int->S.Int.min(1) t->Assert.deepEqual( - 0->S.serializeToUnknownWith(struct), + 0->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Number must be greater than or equal to 1"), @@ -47,20 +47,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.int->S.Int.min(~message="Custom", 1) + let schema = S.int->S.Int.min(~message="Custom", 1) t->Assert.deepEqual( - 0->S.parseAnyWith(struct), + 0->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.int->S.Int.min(1) + let schema = S.int->S.Int.min(1) t->Assert.deepEqual( - struct->S.Int.refinements, + schema->S.Int.refinements, [{kind: Min({value: 1}), message: "Number must be greater than or equal to 1"}], (), ) diff --git a/packages/tests/src/core/S_Int_port_test.res b/packages/tests/src/core/S_Int_port_test.res index 1b86c4b6..67e3c692 100644 --- a/packages/tests/src/core/S_Int_port_test.res +++ b/packages/tests/src/core/S_Int_port_test.res @@ -1,32 +1,32 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.int->S.Int.port + let schema = S.int->S.Int.port - t->Assert.deepEqual(8080->S.parseAnyWith(struct), Ok(8080), ()) + t->Assert.deepEqual(8080->S.parseAnyWith(schema), Ok(8080), ()) }) test("Fails to parse invalid data", t => { - let struct = S.int->S.Int.port + let schema = S.int->S.Int.port t->Assert.deepEqual( - 65536->S.parseAnyWith(struct), + 65536->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Invalid port"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully serializes valid value", t => { - let struct = S.int->S.Int.port + let schema = S.int->S.Int.port - t->Assert.deepEqual(8080->S.serializeToUnknownWith(struct), Ok(%raw(`8080`)), ()) + t->Assert.deepEqual(8080->S.serializeToUnknownWith(schema), Ok(%raw(`8080`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.int->S.Int.port + let schema = S.int->S.Int.port t->Assert.deepEqual( - -80->S.serializeToUnknownWith(struct), + -80->S.serializeToUnknownWith(schema), Error( U.error({code: OperationFailed("Invalid port"), operation: Serializing, path: S.Path.empty}), ), @@ -35,17 +35,17 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.int->S.Int.port(~message="Custom") + let schema = S.int->S.Int.port(~message="Custom") t->Assert.deepEqual( - 400000->S.parseAnyWith(struct), + 400000->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.int->S.Int.port + let schema = S.int->S.Int.port - t->Assert.deepEqual(struct->S.Int.refinements, [{kind: Port, message: "Invalid port"}], ()) + t->Assert.deepEqual(schema->S.Int.refinements, [{kind: Port, message: "Invalid port"}], ()) }) diff --git a/packages/tests/src/core/S_JsApi_test.ts b/packages/tests/src/core/S_JsApi_test.ts index 4dca1c8e..40226b33 100644 --- a/packages/tests/src/core/S_JsApi_test.ts +++ b/packages/tests/src/core/S_JsApi_test.ts @@ -4,18 +4,18 @@ import { expectType, TypeEqual } from "ts-expect"; import * as S from "../../../../src/S.js"; test("Successfully parses string", (t) => { - const struct = S.string; - const value = S.parseOrThrow(struct, "123"); + const schema = S.string; + const value = S.parseOrThrow(schema, "123"); t.deepEqual(value, "123"); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses string with built-in refinement", (t) => { - const struct = S.String.length(S.string, 5); - const result = S.parse(struct, "123"); + const schema = S.String.length(S.string, 5); + const result = S.parse(schema, "123"); expectType>>(true); @@ -28,7 +28,7 @@ test("Successfully parses string with built-in refinement", (t) => { "Failed parsing at root. Reason: String must be exactly 5 characters long" ); - expectType>>(true); + expectType>>(true); expectType< TypeEqual< typeof result, @@ -41,8 +41,8 @@ test("Successfully parses string with built-in refinement", (t) => { }); test("Successfully parses string with built-in refinement and custom message", (t) => { - const struct = S.String.length(S.string, 5, "Postcode must have 5 symbols"); - const result = S.parse(struct, "123"); + const schema = S.String.length(S.string, 5, "Postcode must have 5 symbols"); + const result = S.parse(schema, "123"); if (result.success) { t.fail("Should fail"); @@ -53,110 +53,110 @@ test("Successfully parses string with built-in refinement and custom message", ( "Failed parsing at root. Reason: Postcode must have 5 symbols" ); - expectType>>(true); + expectType>>(true); }); test("Successfully parses string with built-in transform", (t) => { - const struct = S.String.trim(S.string); - const value = S.parseOrThrow(struct, " 123"); + const schema = S.String.trim(S.string); + const value = S.parseOrThrow(schema, " 123"); t.deepEqual(value, "123"); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses string with built-in datetime transform", (t) => { - const struct = S.String.datetime(S.string); - const value = S.parseOrThrow(struct, "2020-01-01T00:00:00Z"); + const schema = S.String.datetime(S.string); + const value = S.parseOrThrow(schema, "2020-01-01T00:00:00Z"); t.deepEqual(value, new Date("2020-01-01T00:00:00Z")); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses int", (t) => { - const struct = S.integer; - const value = S.parseOrThrow(struct, 123); + const schema = S.integer; + const value = S.parseOrThrow(schema, 123); t.deepEqual(value, 123); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses float", (t) => { - const struct = S.number; - const value = S.parseOrThrow(struct, 123.4); + const schema = S.number; + const value = S.parseOrThrow(schema, 123.4); t.deepEqual(value, 123.4); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses bool", (t) => { - const struct = S.boolean; - const value = S.parseOrThrow(struct, true); + const schema = S.boolean; + const value = S.parseOrThrow(schema, true); t.deepEqual(value, true); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses unknown", (t) => { - const struct = S.unknown; - const value = S.parseOrThrow(struct, true); + const schema = S.unknown; + const value = S.parseOrThrow(schema, true); t.deepEqual(value, true); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses json", (t) => { - const struct = S.json; - const value = S.parseOrThrow(struct, true); + const schema = S.json; + const value = S.parseOrThrow(schema, true); t.deepEqual(value, true); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses undefined", (t) => { - const struct = S.undefined; - const value = S.parseOrThrow(struct, undefined); + const schema = S.undefined; + const value = S.parseOrThrow(schema, undefined); t.deepEqual(value, undefined); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Fails to parse never", (t) => { - const struct = S.never; + const schema = S.never; t.throws( () => { - const value = S.parseOrThrow(struct, true); + const value = S.parseOrThrow(schema, true); - expectType>>(true); + expectType>>(true); expectType>(true); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: "Failed parsing at root. Reason: Expected Never, received true", } ); }); test("Can get a reason from an error", (t) => { - const struct = S.never; + const schema = S.never; - const result = S.parse(struct, true); + const result = S.parse(schema, true); if (result.success) { t.fail("Should fail"); @@ -166,117 +166,117 @@ test("Can get a reason from an error", (t) => { }); test("Successfully parses array", (t) => { - const struct = S.array(S.string); - const value = S.parseOrThrow(struct, ["foo"]); + const schema = S.array(S.string); + const value = S.parseOrThrow(schema, ["foo"]); t.deepEqual(value, ["foo"]); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses record", (t) => { - const struct = S.record(S.string); - const value = S.parseOrThrow(struct, { foo: "bar" }); + const schema = S.record(S.string); + const value = S.parseOrThrow(schema, { foo: "bar" }); t.deepEqual(value, { foo: "bar" }); expectType< TypeEqual< - typeof struct, - S.Struct, Record> + typeof schema, + S.Schema, Record> > >(true); expectType>>(true); }); test("Successfully parses JSON string", (t) => { - const struct = S.jsonString(S.boolean); - const value = S.parseOrThrow(struct, `true`); + const schema = S.jsonString(S.boolean); + const value = S.parseOrThrow(schema, `true`); t.deepEqual(value, true); - expectType>>(true); + expectType>>(true); expectType>(true); }); test("Successfully parses optional string", (t) => { - const struct = S.optional(S.string); - const value1 = S.parseOrThrow(struct, "foo"); - const value2 = S.parseOrThrow(struct, undefined); + const schema = S.optional(S.string); + const value1 = S.parseOrThrow(schema, "foo"); + const value2 = S.parseOrThrow(schema, undefined); t.deepEqual(value1, "foo"); t.deepEqual(value2, undefined); expectType< - TypeEqual, typeof struct> + TypeEqual, typeof schema> >(true); expectType>(true); expectType>(true); }); -test("Successfully parses struct wrapped in optional multiple times", (t) => { - const struct = S.optional(S.optional(S.optional(S.string))); - const value1 = S.parseOrThrow(struct, "foo"); - const value2 = S.parseOrThrow(struct, undefined); +test("Successfully parses schema wrapped in optional multiple times", (t) => { + const schema = S.optional(S.optional(S.optional(S.string))); + const value1 = S.parseOrThrow(schema, "foo"); + const value2 = S.parseOrThrow(schema, undefined); t.deepEqual(value1, "foo"); t.deepEqual(value2, undefined); expectType< - TypeEqual, typeof struct> + TypeEqual, typeof schema> >(true); expectType>(true); expectType>(true); }); test("Successfully parses nullable string", (t) => { - const struct = S.nullable(S.string); - const value1 = S.parseOrThrow(struct, "foo"); - const value2 = S.parseOrThrow(struct, null); + const schema = S.nullable(S.string); + const value1 = S.parseOrThrow(schema, "foo"); + const value2 = S.parseOrThrow(schema, null); t.deepEqual(value1, "foo"); t.deepEqual(value2, undefined); expectType< - TypeEqual, typeof struct> + TypeEqual, typeof schema> >(true); expectType>(true); expectType>(true); }); -test("Successfully parses struct wrapped in nullable multiple times", (t) => { - const struct = S.nullable(S.nullable(S.nullable(S.string))); - const value1 = S.parseOrThrow(struct, "foo"); - const value2 = S.parseOrThrow(struct, null); +test("Successfully parses schema wrapped in nullable multiple times", (t) => { + const schema = S.nullable(S.nullable(S.nullable(S.string))); + const value1 = S.parseOrThrow(schema, "foo"); + const value2 = S.parseOrThrow(schema, null); t.deepEqual(value1, "foo"); t.deepEqual(value2, undefined); expectType< - TypeEqual, typeof struct> + TypeEqual, typeof schema> >(true); expectType>(true); expectType>(true); }); test("Fails to parse with invalid data", (t) => { - const struct = S.string; + const schema = S.string; t.throws( () => { - S.parseOrThrow(struct, 123); + S.parseOrThrow(schema, 123); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: "Failed parsing at root. Reason: Expected String, received 123", } ); }); test("Successfully serializes with valid value", (t) => { - const struct = S.string; - const result = S.serializeOrThrow(struct, "123"); + const schema = S.string; + const result = S.serializeOrThrow(schema, "123"); t.deepEqual(result, "123"); @@ -284,23 +284,23 @@ test("Successfully serializes with valid value", (t) => { }); test("Fails to serialize never", (t) => { - const struct = S.never; + const schema = S.never; t.throws( () => { // @ts-ignore - S.serializeOrThrow(struct, "123"); + S.serializeOrThrow(schema, "123"); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: `Failed serializing at root. Reason: Expected Never, received "123"`, } ); }); test("Successfully parses with transform to another type", (t) => { - const struct = S.transform(S.string, (string) => Number(string)); - const value = S.parseOrThrow(struct, "123"); + const schema = S.transform(S.string, (string) => Number(string)); + const value = S.parseOrThrow(schema, "123"); t.deepEqual(value, 123); @@ -308,30 +308,30 @@ test("Successfully parses with transform to another type", (t) => { }); test("Fails to parse with transform with user error", (t) => { - const struct = S.transform(S.string, (string, s) => { + const schema = S.transform(S.string, (string, s) => { const number = Number(string); if (Number.isNaN(number)) { throw s.fail("Invalid number"); } return number; }); - const value = S.parseOrThrow(struct, "123"); + const value = S.parseOrThrow(schema, "123"); t.deepEqual(value, 123); expectType>(true); t.throws( () => { - S.parseOrThrow(struct, "asdf"); + S.parseOrThrow(schema, "asdf"); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: "Failed parsing at root. Reason: Invalid number", } ); }); test("Successfully serializes with transform to another type", (t) => { - const struct = S.transform( + const schema = S.transform( S.string, (string) => Number(string), (number) => { @@ -339,7 +339,7 @@ test("Successfully serializes with transform to another type", (t) => { return number.toString(); } ); - const result = S.serializeOrThrow(struct, 123); + const result = S.serializeOrThrow(schema, 123); t.deepEqual(result, "123"); @@ -347,10 +347,10 @@ test("Successfully serializes with transform to another type", (t) => { }); test("Successfully parses with refine", (t) => { - const struct = S.refine(S.string, (string) => { + const schema = S.refine(S.string, (string) => { expectType>(true); }); - const value = S.parseOrThrow(struct, "123"); + const value = S.parseOrThrow(schema, "123"); t.deepEqual(value, "123"); @@ -358,10 +358,10 @@ test("Successfully parses with refine", (t) => { }); test("Successfully serializes with refine", (t) => { - const struct = S.refine(S.string, (string) => { + const schema = S.refine(S.string, (string) => { expectType>(true); }); - const result = S.serializeOrThrow(struct, "123"); + const result = S.serializeOrThrow(schema, "123"); t.deepEqual(result, "123"); @@ -369,40 +369,40 @@ test("Successfully serializes with refine", (t) => { }); test("Fails to parses with refine raising an error", (t) => { - const struct = S.refine(S.string, (_, s) => { + const schema = S.refine(S.string, (_, s) => { s.fail("User error"); }); t.throws( () => { - S.parseOrThrow(struct, "123"); + S.parseOrThrow(schema, "123"); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: "Failed parsing at root. Reason: User error", } ); }); -test("Successfully parses async struct", async (t) => { - const struct = S.asyncParserRefine(S.string, async (string) => { +test("Successfully parses async schema", async (t) => { + const schema = S.asyncParserRefine(S.string, async (string) => { expectType>(true); }); - const value = await S.parseAsync(struct, "123"); + const value = await S.parseAsync(schema, "123"); t.deepEqual(value, { success: true, value: "123" }); expectType>>(true); }); -test("Fails to parses async struct", async (t) => { - const struct = S.asyncParserRefine(S.string, async (_, s) => { +test("Fails to parses async schema", async (t) => { + const schema = S.asyncParserRefine(S.string, async (_, s) => { return Promise.resolve().then(() => { s.fail("User error"); }); }); - const result = await S.parseAsync(struct, "123"); + const result = await S.parseAsync(schema, "123"); if (result.success) { t.fail("Should fail"); @@ -412,8 +412,8 @@ test("Fails to parses async struct", async (t) => { t.true(result.error instanceof S.Error); }); -test("Custom string struct", (t) => { - const struct = S.custom( +test("Custom string schema", (t) => { + const schema = S.custom( "Postcode", (unknown, s) => { if (typeof unknown !== "string") { @@ -430,37 +430,37 @@ test("Custom string struct", (t) => { } ); - t.deepEqual(S.parseOrThrow(struct, "12345"), "12345"); - t.deepEqual(S.serializeOrThrow(struct, "12345"), "12345"); + t.deepEqual(S.parseOrThrow(schema, "12345"), "12345"); + t.deepEqual(S.serializeOrThrow(schema, "12345"), "12345"); t.throws( () => { - S.parseOrThrow(struct, 123); + S.parseOrThrow(schema, 123); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: "Failed parsing at root. Reason: Postcode should be a string", } ); t.throws( () => { - S.parseOrThrow(struct, "123"); + S.parseOrThrow(schema, "123"); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: "Failed parsing at root. Reason: Postcode should be 5 characters", } ); - expectType>>(true); + expectType>>(true); }); test("Successfully parses object by provided shape", (t) => { - const struct = S.object({ + const schema = S.object({ foo: S.string, bar: S.boolean, }); - const value = S.parseOrThrow(struct, { + const value = S.parseOrThrow(schema, { foo: "bar", bar: true, }); @@ -472,8 +472,8 @@ test("Successfully parses object by provided shape", (t) => { expectType< TypeEqual< - typeof struct, - S.Struct< + typeof schema, + S.Schema< { foo: string; bar: boolean; @@ -497,11 +497,11 @@ test("Successfully parses object by provided shape", (t) => { }); test("Successfully parses object with field names transform", (t) => { - const struct = S.object((s) => ({ + const schema = S.object((s) => ({ foo: s.field("Foo", S.string), bar: s.field("Bar", S.boolean), })); - const value = S.parseOrThrow(struct, { + const value = S.parseOrThrow(schema, { Foo: "bar", Bar: true, }); @@ -513,8 +513,8 @@ test("Successfully parses object with field names transform", (t) => { expectType< TypeEqual< - typeof struct, - S.Struct< + typeof schema, + S.Schema< { foo: string; bar: boolean; @@ -535,11 +535,11 @@ test("Successfully parses object with field names transform", (t) => { }); test("Successfully parses object with transformed field", (t) => { - const struct = S.object({ + const schema = S.object({ foo: S.transform(S.string, (string) => Number(string)), bar: S.boolean, }); - const value = S.parseOrThrow(struct, { + const value = S.parseOrThrow(schema, { foo: "123", bar: true, }); @@ -551,8 +551,8 @@ test("Successfully parses object with transformed field", (t) => { expectType< TypeEqual< - typeof struct, - S.Struct< + typeof schema, + S.Schema< { foo: number; bar: boolean; @@ -576,7 +576,7 @@ test("Successfully parses object with transformed field", (t) => { }); test("Fails to parse strict object with exccess fields", (t) => { - const struct = S.Object.strict( + const schema = S.Object.strict( S.object({ foo: S.string, }) @@ -584,14 +584,14 @@ test("Fails to parse strict object with exccess fields", (t) => { t.throws( () => { - const value = S.parseOrThrow(struct, { + const value = S.parseOrThrow(schema, { foo: "bar", bar: true, }); expectType< TypeEqual< - typeof struct, - S.Struct< + typeof schema, + S.Schema< { foo: string; }, @@ -611,14 +611,14 @@ test("Fails to parse strict object with exccess fields", (t) => { >(true); }, { - name: "RescriptStructError", + name: "RescriptSchemaError", message: `Failed parsing at root. Reason: Encountered disallowed excess key "bar" on an object. Use Deprecated to ignore a specific field, or S.Object.strip to ignore excess keys completely`, } ); }); test("Resets object strict mode with strip method", (t) => { - const struct = S.Object.strip( + const schema = S.Object.strip( S.Object.strict( S.object({ foo: S.string, @@ -626,7 +626,7 @@ test("Resets object strict mode with strip method", (t) => { ) ); - const value = S.parseOrThrow(struct, { + const value = S.parseOrThrow(schema, { foo: "bar", bar: true, }); @@ -635,8 +635,8 @@ test("Resets object strict mode with strip method", (t) => { expectType< TypeEqual< - typeof struct, - S.Struct< + typeof schema, + S.Schema< { foo: string; }, @@ -657,7 +657,7 @@ test("Resets object strict mode with strip method", (t) => { }); test("Successfully parses intersected objects", (t) => { - const struct = S.merge( + const schema = S.merge( S.object({ foo: S.string, bar: S.boolean, @@ -669,8 +669,8 @@ test("Successfully parses intersected objects", (t) => { expectType< TypeEqual< - typeof struct, - S.Struct< + typeof schema, + S.Schema< { foo: string; bar: boolean; @@ -682,7 +682,7 @@ test("Successfully parses intersected objects", (t) => { > >(true); - const result = S.parse(struct, { + const result = S.parse(schema, { foo: "bar", bar: true, }); @@ -695,7 +695,7 @@ test("Successfully parses intersected objects", (t) => { `Failed parsing at ["baz"]. Reason: Expected String, received undefined` ); - const value = S.parseOrThrow(struct, { + const value = S.parseOrThrow(schema, { foo: "bar", baz: "baz", bar: true, @@ -708,7 +708,7 @@ test("Successfully parses intersected objects", (t) => { }); test("Successfully parses intersected objects with transform", (t) => { - const struct = S.merge( + const schema = S.merge( S.transform( S.object({ foo: S.string, @@ -725,8 +725,8 @@ test("Successfully parses intersected objects with transform", (t) => { expectType< TypeEqual< - typeof struct, - S.Struct< + typeof schema, + S.Schema< { abc: string; } & { @@ -737,7 +737,7 @@ test("Successfully parses intersected objects with transform", (t) => { > >(true); - const result = S.parse(struct, { + const result = S.parse(schema, { foo: "bar", bar: true, }); @@ -750,7 +750,7 @@ test("Successfully parses intersected objects with transform", (t) => { `Failed parsing at ["baz"]. Reason: Expected String, received undefined` ); - const value = S.parseOrThrow(struct, { + const value = S.parseOrThrow(schema, { foo: "bar", baz: "baz", bar: true, @@ -762,7 +762,7 @@ test("Successfully parses intersected objects with transform", (t) => { }); test("Fails to serialize merge. Not supported yet", (t) => { - const struct = S.merge( + const schema = S.merge( S.object({ foo: S.string, bar: S.boolean, @@ -772,7 +772,7 @@ test("Fails to serialize merge. Not supported yet", (t) => { }) ); - const result = S.serialize(struct, { + const result = S.serialize(schema, { foo: "bar", bar: true, baz: "string", @@ -787,8 +787,8 @@ test("Fails to serialize merge. Not supported yet", (t) => { ); }); -test("Name of merge struct", (t) => { - const struct = S.merge( +test("Name of merge schema", (t) => { + const schema = S.merge( S.object({ foo: S.string, bar: S.boolean, @@ -799,7 +799,7 @@ test("Name of merge struct", (t) => { ); t.is( - S.name(struct), + S.name(schema), `Object({"foo": String, "bar": Bool}) & Object({"baz": String})` ); }); @@ -809,8 +809,8 @@ test("setName", (t) => { }); test("Successfully parses and returns result", (t) => { - const struct = S.string; - const value = S.parse(struct, "123"); + const schema = S.string; + const value = S.parse(schema, "123"); t.deepEqual(value, { success: true, value: "123" }); @@ -839,8 +839,8 @@ test("Successfully parses and returns result", (t) => { }); test("Successfully serializes and returns result", (t) => { - const struct = S.string; - const value = S.serialize(struct, "123"); + const schema = S.string; + const value = S.serialize(schema, "123"); t.deepEqual(value, { success: true, value: "123" }); @@ -868,196 +868,196 @@ test("Successfully serializes and returns result", (t) => { }); test("Successfully parses union", (t) => { - const struct = S.union([S.string, S.number]); - const value = S.parse(struct, "123"); + const schema = S.union([S.string, S.number]); + const value = S.parse(schema, "123"); t.deepEqual(value, { success: true, value: "123" }); expectType< - TypeEqual> + TypeEqual> >(true); }); test("Successfully parses union with transformed items", (t) => { - const struct = S.union([ + const schema = S.union([ S.transform(S.string, (string) => Number(string)), S.number, ]); - const value = S.parse(struct, "123"); + const value = S.parse(schema, "123"); t.deepEqual(value, { success: true, value: 123 }); - expectType>>(true); + expectType>>(true); }); test("String literal", (t) => { - const struct = S.literal("tuna"); + const schema = S.literal("tuna"); - t.deepEqual(S.parseOrThrow(struct, "tuna"), "tuna"); + t.deepEqual(S.parseOrThrow(schema, "tuna"), "tuna"); - expectType>>(true); + expectType>>(true); }); test("Boolean literal", (t) => { - const struct = S.literal(true); + const schema = S.literal(true); - t.deepEqual(S.parseOrThrow(struct, true), true); + t.deepEqual(S.parseOrThrow(schema, true), true); - expectType>>(true); + expectType>>(true); }); test("Number literal", (t) => { - const struct = S.literal(123); + const schema = S.literal(123); - t.deepEqual(S.parseOrThrow(struct, 123), 123); + t.deepEqual(S.parseOrThrow(schema, 123), 123); - expectType>>(true); + expectType>>(true); }); test("Undefined literal", (t) => { - const struct = S.literal(undefined); + const schema = S.literal(undefined); - t.deepEqual(S.parseOrThrow(struct, undefined), undefined); + t.deepEqual(S.parseOrThrow(schema, undefined), undefined); - expectType>>(true); + expectType>>(true); }); test("Null literal", (t) => { - const struct = S.literal(null); + const schema = S.literal(null); - t.deepEqual(S.parseOrThrow(struct, null), null); + t.deepEqual(S.parseOrThrow(schema, null), null); - expectType>>(true); + expectType>>(true); }); test("Symbol literal", (t) => { let symbol = Symbol(); - const struct = S.literal(symbol); + const schema = S.literal(symbol); - t.deepEqual(S.parseOrThrow(struct, symbol), symbol); + t.deepEqual(S.parseOrThrow(schema, symbol), symbol); - expectType>>(true); + expectType>>(true); }); test("BigInt literal", (t) => { - const struct = S.literal(123n); + const schema = S.literal(123n); - t.deepEqual(S.parseOrThrow(struct, 123n), 123n); + t.deepEqual(S.parseOrThrow(schema, 123n), 123n); - expectType>>(true); + expectType>>(true); }); test("NaN literal", (t) => { - const struct = S.literal(NaN); + const schema = S.literal(NaN); - t.deepEqual(S.parseOrThrow(struct, NaN), NaN); + t.deepEqual(S.parseOrThrow(schema, NaN), NaN); - expectType>>(true); + expectType>>(true); }); test("Tuple literal", (t) => { - const cliArgsStruct = S.literal(["help", "lint"] as const); + const cliArgsSchema = S.literal(["help", "lint"] as const); - t.deepEqual(S.parseOrThrow(cliArgsStruct, ["help", "lint"]), [ + t.deepEqual(S.parseOrThrow(cliArgsSchema, ["help", "lint"]), [ "help", "lint", ]); expectType< TypeEqual< - typeof cliArgsStruct, - S.Struct + typeof cliArgsSchema, + S.Schema > >(true); }); test("Correctly infers type", (t) => { - const struct = S.transform(S.string, Number); - expectType>>(true); - expectType, string>>(true); - expectType, number>>(true); + const schema = S.transform(S.string, Number); + expectType>>(true); + expectType, string>>(true); + expectType, number>>(true); t.pass(); }); test("Successfully parses undefined using the default value", (t) => { - const struct = S.optional(S.string, "foo"); + const schema = S.optional(S.string, "foo"); - const value = S.parseOrThrow(struct, undefined); + const value = S.parseOrThrow(schema, undefined); t.deepEqual(value, "foo"); - expectType>>( + expectType>>( true ); }); test("Successfully parses undefined using the default value from callback", (t) => { - const struct = S.optional(S.string, () => "foo"); + const schema = S.optional(S.string, () => "foo"); - const value = S.parseOrThrow(struct, undefined); + const value = S.parseOrThrow(schema, undefined); t.deepEqual(value, "foo"); - expectType>>( + expectType>>( true ); }); -test("Creates struct with description", (t) => { - const undocumentedStringStruct = S.string; +test("Creates schema with description", (t) => { + const undocumentedStringSchema = S.string; expectType< - TypeEqual> + TypeEqual> >(true); - const documentedStringStruct = S.describe( - undocumentedStringStruct, + const documentedStringSchema = S.describe( + undocumentedStringSchema, "A useful bit of text, if you know what to do with it." ); expectType< - TypeEqual> + TypeEqual> >(true); - const descriptionResult = S.description(documentedStringStruct); + const descriptionResult = S.description(documentedStringSchema); expectType>(true); - t.deepEqual(S.description(undocumentedStringStruct), undefined); + t.deepEqual(S.description(undocumentedStringSchema), undefined); t.deepEqual( - S.description(documentedStringStruct), + S.description(documentedStringSchema), "A useful bit of text, if you know what to do with it." ); }); test("Empty tuple", (t) => { - const struct = S.tuple([]); + const schema = S.tuple([]); - t.deepEqual(S.parseOrThrow(struct, []), []); + t.deepEqual(S.parseOrThrow(schema, []), []); - expectType>>(true); + expectType>>(true); }); test("Tuple with single element", (t) => { - const struct = S.tuple([S.transform(S.string, (s) => Number(s))]); + const schema = S.tuple([S.transform(S.string, (s) => Number(s))]); - t.deepEqual(S.parseOrThrow(struct, ["123"]), [123]); + t.deepEqual(S.parseOrThrow(schema, ["123"]), [123]); - expectType>>(true); + expectType>>(true); }); test("Tuple with multiple elements", (t) => { - const struct = S.tuple([S.transform(S.string, (s) => Number(s)), S.number]); + const schema = S.tuple([S.transform(S.string, (s) => Number(s)), S.number]); - t.deepEqual(S.parseOrThrow(struct, ["123", 123]), [123, 123]); + t.deepEqual(S.parseOrThrow(schema, ["123", 123]), [123, 123]); expectType< - TypeEqual> + TypeEqual> >(true); }); test("Tuple with transform to object", (t) => { - let pointStruct = S.tuple((s) => { + let pointSchema = S.tuple((s) => { s.tag(0, "point"); return { x: s.item(1, S.integer), @@ -1065,12 +1065,12 @@ test("Tuple with transform to object", (t) => { }; }); - t.deepEqual(S.parseOrThrow(pointStruct, ["point", 1, -4]), { x: 1, y: -4 }); + t.deepEqual(S.parseOrThrow(pointSchema, ["point", 1, -4]), { x: 1, y: -4 }); expectType< TypeEqual< - typeof pointStruct, - S.Struct< + typeof pointSchema, + S.Schema< { x: number; y: number; @@ -1082,25 +1082,25 @@ test("Tuple with transform to object", (t) => { }); test("Example", (t) => { - // Create login struct with email and password - const loginStruct = S.object({ + // Create login schema with email and password + const loginSchema = S.object({ email: S.String.email(S.string), password: S.String.min(S.string, 8), }); - // Infer output TypeScript type of login struct - type LoginData = S.Output; // { email: string; password: string } + // Infer output TypeScript type of login schema + type LoginData = S.Output; // { email: string; password: string } t.throws( () => { // Throws the S.Error(`Failed parsing at ["email"]. Reason: Invalid email address`) - S.parseOrThrow(loginStruct, { email: "", password: "" }); + S.parseOrThrow(loginSchema, { email: "", password: "" }); }, { message: `Failed parsing at ["email"]. Reason: Invalid email address` } ); // Returns data as { email: string; password: string } - const result = S.parseOrThrow(loginStruct, { + const result = S.parseOrThrow(loginSchema, { email: "jane@example.com", password: "12345678", }); @@ -1112,8 +1112,8 @@ test("Example", (t) => { expectType< TypeEqual< - typeof loginStruct, - S.Struct< + typeof loginSchema, + S.Schema< { email: string; password: string }, { email: string; password: string } > diff --git a/packages/tests/src/core/S_Object_unknownKeys_test.res b/packages/tests/src/core/S_Object_unknownKeys_test.res index 7009ceda..0ea5af0a 100644 --- a/packages/tests/src/core/S_Object_unknownKeys_test.res +++ b/packages/tests/src/core/S_Object_unknownKeys_test.res @@ -5,20 +5,20 @@ type objectWithOneField = {key: string} test("Successfully parses Object with unknown keys by default", t => { let any = %raw(`{key: "value", unknownKey: "value2"}`) - let struct = S.object(s => s.field("key", S.string)) + let schema = S.object(s => s.field("key", S.string)) - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok("value"), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok("value"), ()) }) test("Fails fast and shows only one excees key in the error message", t => { - let struct = S.object(s => + let schema = S.object(s => { "key": s.field("key", S.string), } )->S.Object.strict t->Assert.deepEqual( - %raw(`{key: "value", unknownKey: "value2", unknownKey2: "value2"}`)->S.parseAnyWith(struct), + %raw(`{key: "value", unknownKey: "value2", unknownKey2: "value2"}`)->S.parseAnyWith(schema), Error(U.error({code: ExcessField("unknownKey"), operation: Parsing, path: S.Path.empty})), (), ) @@ -28,22 +28,22 @@ test("Successfully parses Object with unknown keys when Strip strategy applyed", let value = "value" let any = %raw(`{key: "value", unknownKey: "value2"}`) - let struct = S.object(s => s.field("key", S.string))->S.Object.strip + let schema = S.object(s => s.field("key", S.string))->S.Object.strip - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Works correctly when the same unknown keys strategy applyed multiple times", t => { let value = "value" let any = %raw(`{key: "value", unknownKey: "value2"}`) - let struct = + let schema = S.object(s => s.field("key", S.string))->S.Object.strip->S.Object.strip->S.Object.strip - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) -test("Doesn't raise an error when unknown keys strategy applyed to a non Object struct", t => { +test("Doesn't raise an error when unknown keys strategy applyed to a non Object schema", t => { t->Assert.notThrows(() => { S.string->S.Object.strip->ignore }, ()) @@ -55,10 +55,10 @@ test("Doesn't raise an error when unknown keys strategy applyed to a non Object test("Can reset unknown keys strategy applying Strict strategy", t => { let any = %raw(`{key: "value", unknownKey: "value2"}`) - let struct = S.object(s => s.field("key", S.string))->S.Object.strip->S.Object.strict + let schema = S.object(s => s.field("key", S.string))->S.Object.strip->S.Object.strict t->Assert.deepEqual( - any->S.parseAnyWith(struct), + any->S.parseAnyWith(schema), Error(U.error({code: ExcessField("unknownKey"), operation: Parsing, path: S.Path.empty})), (), ) diff --git a/packages/tests/src/core/S_Option_default_test.res b/packages/tests/src/core/S_Option_default_test.res index cd9fe629..fe9be002 100644 --- a/packages/tests/src/core/S_Option_default_test.res +++ b/packages/tests/src/core/S_Option_default_test.res @@ -1,13 +1,13 @@ open Ava test("Gets default value when Option.getOr is used", t => { - let struct = S.option(S.float)->S.Option.getOr(123.) + let schema = S.option(S.float)->S.Option.getOr(123.) - t->Assert.deepEqual(struct->S.Option.default, Some(Value(123.->(U.magic: float => unknown))), ()) + t->Assert.deepEqual(schema->S.Option.default, Some(Value(123.->(U.magic: float => unknown))), ()) }) test("Returns the last default value", t => { - let struct = + let schema = S.option(S.float) ->S.Option.getOr(123.) ->S.transform(_ => { @@ -21,7 +21,7 @@ test("Returns the last default value", t => { ->S.Option.getOr("not positive") t->Assert.deepEqual( - struct->S.Option.default, + schema->S.Option.default, Some(Value("not positive"->(U.magic: string => unknown))), (), ) @@ -29,17 +29,17 @@ test("Returns the last default value", t => { test("Gets default value when Option.getOrWith is used", t => { let cb = () => 123. - let struct = S.option(S.float)->S.Option.getOrWith(cb) + let schema = S.option(S.float)->S.Option.getOrWith(cb) t->Assert.deepEqual( - struct->S.Option.default, + schema->S.Option.default, Some(Callback(cb->(U.magic: (unit => float) => unit => unknown))), (), ) }) -test("Doesn't get default value for structs without default", t => { - let struct = S.float +test("Doesn't get default value for schemas without default", t => { + let schema = S.float - t->Assert.deepEqual(struct->S.Option.default, None, ()) + t->Assert.deepEqual(schema->S.Option.default, None, ()) }) diff --git a/packages/tests/src/core/S_Option_getOrWith_test.res b/packages/tests/src/core/S_Option_getOrWith_test.res index 9987c78f..d5ae1567 100644 --- a/packages/tests/src/core/S_Option_getOrWith_test.res +++ b/packages/tests/src/core/S_Option_getOrWith_test.res @@ -5,46 +5,46 @@ test("Uses default value when parsing optional unknown primitive", t => { let value = 123. let any = %raw(`undefined`) - let struct = S.float->S.option->S.Option.getOrWith(() => value) + let schema = S.float->S.option->S.Option.getOrWith(() => value) - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Uses default value when nullable optional unknown primitive", t => { let value = 123. let any = %raw(`null`) - let struct = S.float->S.null->S.Option.getOrWith(() => value) + let schema = S.float->S.null->S.Option.getOrWith(() => value) - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Successfully parses with default when provided JS undefined", t => { - let struct = S.bool->S.option->S.Option.getOrWith(() => false) + let schema = S.bool->S.option->S.Option.getOrWith(() => false) - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok(false), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok(false), ()) }) test("Successfully parses with default when provided primitive", t => { - let struct = S.bool->S.option->S.Option.getOrWith(() => false) + let schema = S.bool->S.option->S.Option.getOrWith(() => false) - t->Assert.deepEqual(%raw(`true`)->S.parseAnyWith(struct), Ok(true), ()) + t->Assert.deepEqual(%raw(`true`)->S.parseAnyWith(schema), Ok(true), ()) }) test("Successfully parses nested option with default value", t => { - let struct = S.option(S.bool)->S.option->S.Option.getOrWith(() => Some(true)) + let schema = S.option(S.bool)->S.option->S.Option.getOrWith(() => Some(true)) - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok(Some(true)), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok(Some(true)), ()) }) test("Fails to parse data with default", t => { - let struct = S.bool->S.option->S.Option.getOrWith(() => false) + let schema = S.bool->S.option->S.Option.getOrWith(() => false) t->Assert.deepEqual( - %raw(`"string"`)->S.parseAnyWith(struct), + %raw(`"string"`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`"string"`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`"string"`)}), operation: Parsing, path: S.Path.empty, }), @@ -53,41 +53,41 @@ test("Fails to parse data with default", t => { ) }) -test("Successfully serializes struct with transformation", t => { - let struct = S.string->S.String.trim->S.option->S.Option.getOrWith(() => "default") +test("Successfully serializes schema with transformation", t => { + let schema = S.string->S.String.trim->S.option->S.Option.getOrWith(() => "default") - t->Assert.deepEqual(" abc"->S.serializeToUnknownWith(struct), Ok(%raw(`"abc"`)), ()) + t->Assert.deepEqual(" abc"->S.serializeToUnknownWith(schema), Ok(%raw(`"abc"`)), ()) }) test("Compiled parse code snapshot", t => { - let struct = S.bool->S.option->S.Option.getOrWith(() => false) + let schema = S.bool->S.option->S.Option.getOrWith(() => false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(i!==void 0&&(typeof i!=="boolean")){e[1](i)}if(i!==void 0){v0=i}else{v0=void 0}return v0===void 0?e[0]():v0}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = + let schema = S.bool ->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)}) ->S.option ->S.Option.getOrWith(() => false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v3;if(i!==void 0&&(typeof i!=="boolean")){e[2](i)}if(i!==void 0){let v1;v1=e[0](i);v0=v1}else{v0=()=>Promise.resolve(void 0)}v3=()=>v0().then(v2=>{return v2===void 0?e[1]():v2});return v3}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.bool->S.option->S.Option.getOrWith(() => false) + let schema = S.bool->S.option->S.Option.getOrWith(() => false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;if(i!==void 0){v0=e[0](i)}else{v0=void 0}return v0}`, ) diff --git a/packages/tests/src/core/S_Option_getOr_test.res b/packages/tests/src/core/S_Option_getOr_test.res index 7f65e45a..4beec612 100644 --- a/packages/tests/src/core/S_Option_getOr_test.res +++ b/packages/tests/src/core/S_Option_getOr_test.res @@ -5,53 +5,53 @@ test("Uses default value when parsing optional unknown primitive", t => { let value = 123. let any = %raw(`undefined`) - let struct = S.float->S.option->S.Option.getOr(value) + let schema = S.float->S.option->S.Option.getOr(value) - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Uses default value when nullable optional unknown primitive", t => { let value = 123. let any = %raw(`null`) - let struct = S.float->S.null->S.Option.getOr(value) + let schema = S.float->S.null->S.Option.getOr(value) - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Successfully parses with default when provided JS undefined", t => { - let struct = S.bool->S.option->S.Option.getOr(false) + let schema = S.bool->S.option->S.Option.getOr(false) - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok(false), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok(false), ()) }) test("Successfully parses with default when provided primitive", t => { - let struct = S.bool->S.option->S.Option.getOr(false) + let schema = S.bool->S.option->S.Option.getOr(false) - t->Assert.deepEqual(%raw(`true`)->S.parseAnyWith(struct), Ok(true), ()) + t->Assert.deepEqual(%raw(`true`)->S.parseAnyWith(schema), Ok(true), ()) }) test("Successfully serializes nested option with default value", t => { - let struct = S.option( + let schema = S.option( S.option(S.option(S.option(S.option(S.option(S.bool)))->S.Option.getOr(Some(Some(true))))), ) t->Assert.deepEqual( - Some(Some(Some(Some(None))))->S.serializeToUnknownWith(struct), + Some(Some(Some(Some(None))))->S.serializeToUnknownWith(schema), Ok(%raw(`undefined`)), (), ) - t->Assert.deepEqual(None->S.serializeToUnknownWith(struct), Ok(%raw(`undefined`)), ()) + t->Assert.deepEqual(None->S.serializeToUnknownWith(schema), Ok(%raw(`undefined`)), ()) }) test("Fails to parse data with default", t => { - let struct = S.bool->S.option->S.Option.getOr(false) + let schema = S.bool->S.option->S.Option.getOr(false) t->Assert.deepEqual( - %raw(`"string"`)->S.parseAnyWith(struct), + %raw(`"string"`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`"string"`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`"string"`)}), operation: Parsing, path: S.Path.empty, }), @@ -60,8 +60,8 @@ test("Fails to parse data with default", t => { ) }) -test("Successfully parses struct with transformation", t => { - let struct = +test("Successfully parses schema with transformation", t => { + let schema = S.option(S.float) ->S.Option.getOr(-123.) ->S.transform(_ => { @@ -74,44 +74,44 @@ test("Successfully parses struct with transformation", t => { }) ->S.Option.getOr("not positive") - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok("not positive"), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok("not positive"), ()) }) -test("Successfully serializes struct with transformation", t => { - let struct = S.string->S.String.trim->S.option->S.Option.getOr("default") +test("Successfully serializes schema with transformation", t => { + let schema = S.string->S.String.trim->S.option->S.Option.getOr("default") - t->Assert.deepEqual(" abc"->S.serializeToUnknownWith(struct), Ok(%raw(`"abc"`)), ()) + t->Assert.deepEqual(" abc"->S.serializeToUnknownWith(schema), Ok(%raw(`"abc"`)), ()) }) test("Compiled parse code snapshot", t => { - let struct = S.bool->S.option->S.Option.getOr(false) + let schema = S.bool->S.option->S.Option.getOr(false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(i!==void 0&&(typeof i!=="boolean")){e[1](i)}if(i!==void 0){v0=i}else{v0=void 0}return v0===void 0?e[0]:v0}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = + let schema = S.bool ->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)}) ->S.option ->S.Option.getOr(false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v3;if(i!==void 0&&(typeof i!=="boolean")){e[2](i)}if(i!==void 0){let v1;v1=e[0](i);v0=v1}else{v0=()=>Promise.resolve(void 0)}v3=()=>v0().then(v2=>{return v2===void 0?e[1]:v2});return v3}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.bool->S.option->S.Option.getOr(false) + let schema = S.bool->S.option->S.Option.getOr(false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;if(i!==void 0){v0=e[0](i)}else{v0=void 0}return v0}`, ) diff --git a/packages/tests/src/core/S_String_cuid_test.res b/packages/tests/src/core/S_String_cuid_test.res index 9a67d6c2..3ebc64fa 100644 --- a/packages/tests/src/core/S_String_cuid_test.res +++ b/packages/tests/src/core/S_String_cuid_test.res @@ -1,40 +1,40 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.cuid + let schema = S.string->S.String.cuid t->Assert.deepEqual( - "ckopqwooh000001la8mbi2im9"->S.parseAnyWith(struct), + "ckopqwooh000001la8mbi2im9"->S.parseAnyWith(schema), Ok("ckopqwooh000001la8mbi2im9"), (), ) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.cuid + let schema = S.string->S.String.cuid t->Assert.deepEqual( - "cifjhdsfhsd-invalid-cuid"->S.parseAnyWith(struct), + "cifjhdsfhsd-invalid-cuid"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Invalid CUID"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.cuid + let schema = S.string->S.String.cuid t->Assert.deepEqual( - "ckopqwooh000001la8mbi2im9"->S.serializeToUnknownWith(struct), + "ckopqwooh000001la8mbi2im9"->S.serializeToUnknownWith(schema), Ok(%raw(`"ckopqwooh000001la8mbi2im9"`)), (), ) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.cuid + let schema = S.string->S.String.cuid t->Assert.deepEqual( - "cifjhdsfhsd-invalid-cuid"->S.serializeToUnknownWith(struct), + "cifjhdsfhsd-invalid-cuid"->S.serializeToUnknownWith(schema), Error( U.error({code: OperationFailed("Invalid CUID"), operation: Serializing, path: S.Path.empty}), ), @@ -43,17 +43,17 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.string->S.String.cuid(~message="Custom") + let schema = S.string->S.String.cuid(~message="Custom") t->Assert.deepEqual( - "cifjhdsfhsd-invalid-cuid"->S.parseAnyWith(struct), + "cifjhdsfhsd-invalid-cuid"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.string->S.String.cuid + let schema = S.string->S.String.cuid - t->Assert.deepEqual(struct->S.String.refinements, [{kind: Cuid, message: "Invalid CUID"}], ()) + t->Assert.deepEqual(schema->S.String.refinements, [{kind: Cuid, message: "Invalid CUID"}], ()) }) diff --git a/packages/tests/src/core/S_String_datetime_test.res b/packages/tests/src/core/S_String_datetime_test.res index c51af3bc..9de4ba21 100644 --- a/packages/tests/src/core/S_String_datetime_test.res +++ b/packages/tests/src/core/S_String_datetime_test.res @@ -2,30 +2,30 @@ open Ava open RescriptCore test("Successfully parses valid data", t => { - let struct = S.string->S.String.datetime + let schema = S.string->S.String.datetime t->Assert.deepEqual( - "2020-01-01T00:00:00Z"->S.parseAnyWith(struct), + "2020-01-01T00:00:00Z"->S.parseAnyWith(schema), Ok(Date.fromString("2020-01-01T00:00:00Z")), (), ) t->Assert.deepEqual( - "2020-01-01T00:00:00.123Z"->S.parseAnyWith(struct), + "2020-01-01T00:00:00.123Z"->S.parseAnyWith(schema), Ok(Date.fromString("2020-01-01T00:00:00.123Z")), (), ) t->Assert.deepEqual( - "2020-01-01T00:00:00.123456Z"->S.parseAnyWith(struct), + "2020-01-01T00:00:00.123456Z"->S.parseAnyWith(schema), Ok(Date.fromString("2020-01-01T00:00:00.123456Z")), (), ) }) test("Fails to parse non UTC date string", t => { - let struct = S.string->S.String.datetime + let schema = S.string->S.String.datetime t->Assert.deepEqual( - "Thu Apr 20 2023 10:45:48 GMT+0400"->S.parseAnyWith(struct), + "Thu Apr 20 2023 10:45:48 GMT+0400"->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Invalid datetime string! Must be UTC"), @@ -38,10 +38,10 @@ test("Fails to parse non UTC date string", t => { }) test("Fails to parse UTC date with timezone offset", t => { - let struct = S.string->S.String.datetime + let schema = S.string->S.String.datetime t->Assert.deepEqual( - "2020-01-01T00:00:00+02:00"->S.parseAnyWith(struct), + "2020-01-01T00:00:00+02:00"->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Invalid datetime string! Must be UTC"), @@ -54,40 +54,40 @@ test("Fails to parse UTC date with timezone offset", t => { }) test("Uses custom message on failure", t => { - let struct = S.string->S.String.datetime(~message="Invalid date") + let schema = S.string->S.String.datetime(~message="Invalid date") t->Assert.deepEqual( - "Thu Apr 20 2023 10:45:48 GMT+0400"->S.parseAnyWith(struct), + "Thu Apr 20 2023 10:45:48 GMT+0400"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Invalid date"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.datetime + let schema = S.string->S.String.datetime t->Assert.deepEqual( - Date.fromString("2020-01-01T00:00:00.123Z")->S.serializeToUnknownWith(struct), + Date.fromString("2020-01-01T00:00:00.123Z")->S.serializeToUnknownWith(schema), Ok(%raw(`"2020-01-01T00:00:00.123Z"`)), (), ) }) test("Trims precision to 3 digits when serializing", t => { - let struct = S.string->S.String.datetime + let schema = S.string->S.String.datetime t->Assert.deepEqual( - Date.fromString("2020-01-01T00:00:00.123456Z")->S.serializeToUnknownWith(struct), + Date.fromString("2020-01-01T00:00:00.123456Z")->S.serializeToUnknownWith(schema), Ok(%raw(`"2020-01-01T00:00:00.123Z"`)), (), ) }) test("Returns refinement", t => { - let struct = S.string->S.String.datetime + let schema = S.string->S.String.datetime t->Assert.deepEqual( - struct->S.String.refinements, + schema->S.String.refinements, [{kind: Datetime, message: "Invalid datetime string! Must be UTC"}], (), ) diff --git a/packages/tests/src/core/S_String_email_test.res b/packages/tests/src/core/S_String_email_test.res index 35b0ae81..dfe6fd29 100644 --- a/packages/tests/src/core/S_String_email_test.res +++ b/packages/tests/src/core/S_String_email_test.res @@ -1,16 +1,16 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.email + let schema = S.string->S.String.email - t->Assert.deepEqual("dzakh.dev@gmail.com"->S.parseAnyWith(struct), Ok("dzakh.dev@gmail.com"), ()) + t->Assert.deepEqual("dzakh.dev@gmail.com"->S.parseAnyWith(schema), Ok("dzakh.dev@gmail.com"), ()) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.email + let schema = S.string->S.String.email t->Assert.deepEqual( - "dzakh.dev"->S.parseAnyWith(struct), + "dzakh.dev"->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Invalid email address"), @@ -23,20 +23,20 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.email + let schema = S.string->S.String.email t->Assert.deepEqual( - "dzakh.dev@gmail.com"->S.serializeToUnknownWith(struct), + "dzakh.dev@gmail.com"->S.serializeToUnknownWith(schema), Ok(%raw(`"dzakh.dev@gmail.com"`)), (), ) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.email + let schema = S.string->S.String.email t->Assert.deepEqual( - "dzakh.dev"->S.serializeToUnknownWith(struct), + "dzakh.dev"->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Invalid email address"), @@ -49,20 +49,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.string->S.String.email(~message="Custom") + let schema = S.string->S.String.email(~message="Custom") t->Assert.deepEqual( - "dzakh.dev"->S.parseAnyWith(struct), + "dzakh.dev"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.string->S.String.email + let schema = S.string->S.String.email t->Assert.deepEqual( - struct->S.String.refinements, + schema->S.String.refinements, [{kind: Email, message: "Invalid email address"}], (), ) diff --git a/packages/tests/src/core/S_String_length_test.res b/packages/tests/src/core/S_String_length_test.res index e432e23c..5ab50f32 100644 --- a/packages/tests/src/core/S_String_length_test.res +++ b/packages/tests/src/core/S_String_length_test.res @@ -1,16 +1,16 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.length(1) + let schema = S.string->S.String.length(1) - t->Assert.deepEqual("1"->S.parseAnyWith(struct), Ok("1"), ()) + t->Assert.deepEqual("1"->S.parseAnyWith(schema), Ok("1"), ()) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.length(1) + let schema = S.string->S.String.length(1) t->Assert.deepEqual( - ""->S.parseAnyWith(struct), + ""->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("String must be exactly 1 characters long"), @@ -21,7 +21,7 @@ test("Fails to parse invalid data", t => { (), ) t->Assert.deepEqual( - "1234"->S.parseAnyWith(struct), + "1234"->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("String must be exactly 1 characters long"), @@ -34,16 +34,16 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.length(1) + let schema = S.string->S.String.length(1) - t->Assert.deepEqual("1"->S.serializeToUnknownWith(struct), Ok(%raw(`"1"`)), ()) + t->Assert.deepEqual("1"->S.serializeToUnknownWith(schema), Ok(%raw(`"1"`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.length(1) + let schema = S.string->S.String.length(1) t->Assert.deepEqual( - ""->S.serializeToUnknownWith(struct), + ""->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("String must be exactly 1 characters long"), @@ -54,7 +54,7 @@ test("Fails to serialize invalid value", t => { (), ) t->Assert.deepEqual( - "1234"->S.serializeToUnknownWith(struct), + "1234"->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("String must be exactly 1 characters long"), @@ -67,20 +67,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.string->S.String.length(~message="Custom", 12) + let schema = S.string->S.String.length(~message="Custom", 12) t->Assert.deepEqual( - "123"->S.parseAnyWith(struct), + "123"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.string->S.String.length(4) + let schema = S.string->S.String.length(4) t->Assert.deepEqual( - struct->S.String.refinements, + schema->S.String.refinements, [{kind: Length({length: 4}), message: "String must be exactly 4 characters long"}], (), ) diff --git a/packages/tests/src/core/S_String_max_test.res b/packages/tests/src/core/S_String_max_test.res index 53f861b8..15e5ae57 100644 --- a/packages/tests/src/core/S_String_max_test.res +++ b/packages/tests/src/core/S_String_max_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.max(1) + let schema = S.string->S.String.max(1) - t->Assert.deepEqual("1"->S.parseAnyWith(struct), Ok("1"), ()) - t->Assert.deepEqual(""->S.parseAnyWith(struct), Ok(""), ()) + t->Assert.deepEqual("1"->S.parseAnyWith(schema), Ok("1"), ()) + t->Assert.deepEqual(""->S.parseAnyWith(schema), Ok(""), ()) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.max(1) + let schema = S.string->S.String.max(1) t->Assert.deepEqual( - "1234"->S.parseAnyWith(struct), + "1234"->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("String must be 1 or fewer characters long"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.max(1) + let schema = S.string->S.String.max(1) - t->Assert.deepEqual("1"->S.serializeToUnknownWith(struct), Ok(%raw(`"1"`)), ()) - t->Assert.deepEqual(""->S.serializeToUnknownWith(struct), Ok(%raw(`""`)), ()) + t->Assert.deepEqual("1"->S.serializeToUnknownWith(schema), Ok(%raw(`"1"`)), ()) + t->Assert.deepEqual(""->S.serializeToUnknownWith(schema), Ok(%raw(`""`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.max(1) + let schema = S.string->S.String.max(1) t->Assert.deepEqual( - "1234"->S.serializeToUnknownWith(struct), + "1234"->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("String must be 1 or fewer characters long"), @@ -47,20 +47,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.string->S.String.max(~message="Custom", 1) + let schema = S.string->S.String.max(~message="Custom", 1) t->Assert.deepEqual( - "1234"->S.parseAnyWith(struct), + "1234"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.string->S.String.max(1) + let schema = S.string->S.String.max(1) t->Assert.deepEqual( - struct->S.String.refinements, + schema->S.String.refinements, [{kind: Max({length: 1}), message: "String must be 1 or fewer characters long"}], (), ) diff --git a/packages/tests/src/core/S_String_min_test.res b/packages/tests/src/core/S_String_min_test.res index 5898fdd6..cc6bbfc3 100644 --- a/packages/tests/src/core/S_String_min_test.res +++ b/packages/tests/src/core/S_String_min_test.res @@ -1,17 +1,17 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.min(1) + let schema = S.string->S.String.min(1) - t->Assert.deepEqual("1"->S.parseAnyWith(struct), Ok("1"), ()) - t->Assert.deepEqual("1234"->S.parseAnyWith(struct), Ok("1234"), ()) + t->Assert.deepEqual("1"->S.parseAnyWith(schema), Ok("1"), ()) + t->Assert.deepEqual("1234"->S.parseAnyWith(schema), Ok("1234"), ()) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.min(1) + let schema = S.string->S.String.min(1) t->Assert.deepEqual( - ""->S.parseAnyWith(struct), + ""->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("String must be 1 or more characters long"), @@ -24,17 +24,17 @@ test("Fails to parse invalid data", t => { }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.min(1) + let schema = S.string->S.String.min(1) - t->Assert.deepEqual("1"->S.serializeToUnknownWith(struct), Ok(%raw(`"1"`)), ()) - t->Assert.deepEqual("1234"->S.serializeToUnknownWith(struct), Ok(%raw(`"1234"`)), ()) + t->Assert.deepEqual("1"->S.serializeToUnknownWith(schema), Ok(%raw(`"1"`)), ()) + t->Assert.deepEqual("1234"->S.serializeToUnknownWith(schema), Ok(%raw(`"1234"`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.min(1) + let schema = S.string->S.String.min(1) t->Assert.deepEqual( - ""->S.serializeToUnknownWith(struct), + ""->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("String must be 1 or more characters long"), @@ -47,20 +47,20 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.string->S.String.min(~message="Custom", 1) + let schema = S.string->S.String.min(~message="Custom", 1) t->Assert.deepEqual( - ""->S.parseAnyWith(struct), + ""->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.string->S.String.min(1) + let schema = S.string->S.String.min(1) t->Assert.deepEqual( - struct->S.String.refinements, + schema->S.String.refinements, [{kind: Min({length: 1}), message: "String must be 1 or more characters long"}], (), ) diff --git a/packages/tests/src/core/S_String_pattern_test.res b/packages/tests/src/core/S_String_pattern_test.res index 4086e320..7b70f6a1 100644 --- a/packages/tests/src/core/S_String_pattern_test.res +++ b/packages/tests/src/core/S_String_pattern_test.res @@ -1,70 +1,70 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.pattern(%re(`/[0-9]/`)) + let schema = S.string->S.String.pattern(%re(`/[0-9]/`)) - t->Assert.deepEqual("123"->S.parseAnyWith(struct), Ok("123"), ()) + t->Assert.deepEqual("123"->S.parseAnyWith(schema), Ok("123"), ()) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.pattern(%re(`/[0-9]/`)) + let schema = S.string->S.String.pattern(%re(`/[0-9]/`)) t->Assert.deepEqual( - "abc"->S.parseAnyWith(struct), + "abc"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Invalid"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.pattern(%re(`/[0-9]/`)) + let schema = S.string->S.String.pattern(%re(`/[0-9]/`)) - t->Assert.deepEqual("123"->S.serializeToUnknownWith(struct), Ok(%raw(`"123"`)), ()) + t->Assert.deepEqual("123"->S.serializeToUnknownWith(schema), Ok(%raw(`"123"`)), ()) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.pattern(%re(`/[0-9]/`)) + let schema = S.string->S.String.pattern(%re(`/[0-9]/`)) t->Assert.deepEqual( - "abc"->S.serializeToUnknownWith(struct), + "abc"->S.serializeToUnknownWith(schema), Error(U.error({code: OperationFailed("Invalid"), operation: Serializing, path: S.Path.empty})), (), ) }) test("Returns custom error message", t => { - let struct = S.string->S.String.pattern(~message="Custom", %re(`/[0-9]/`)) + let schema = S.string->S.String.pattern(~message="Custom", %re(`/[0-9]/`)) t->Assert.deepEqual( - "abc"->S.parseAnyWith(struct), + "abc"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Returns refinement", t => { - let struct = S.string->S.String.pattern(%re(`/[0-9]/`)) + let schema = S.string->S.String.pattern(%re(`/[0-9]/`)) t->Assert.deepEqual( - struct->S.String.refinements, + schema->S.String.refinements, [{kind: Pattern({re: %re(`/[0-9]/`)}), message: "Invalid"}], (), ) }) test("Returns multiple refinement", t => { - let struct1 = S.string - let struct2 = struct1->S.String.pattern(~message="Should have digit", %re(`/[0-9]+/`)) - let struct3 = struct2->S.String.pattern(~message="Should have text", %re(`/\w+/`)) + let schema1 = S.string + let schema2 = schema1->S.String.pattern(~message="Should have digit", %re(`/[0-9]+/`)) + let schema3 = schema2->S.String.pattern(~message="Should have text", %re(`/\w+/`)) - t->Assert.deepEqual(struct1->S.String.refinements, [], ()) + t->Assert.deepEqual(schema1->S.String.refinements, [], ()) t->Assert.deepEqual( - struct2->S.String.refinements, + schema2->S.String.refinements, [{kind: Pattern({re: %re(`/[0-9]+/`)}), message: "Should have digit"}], (), ) t->Assert.deepEqual( - struct3->S.String.refinements, + schema3->S.String.refinements, [ {kind: Pattern({re: %re(`/[0-9]+/`)}), message: "Should have digit"}, {kind: Pattern({re: %re(`/\w+/`)}), message: "Should have text"}, diff --git a/packages/tests/src/core/S_String_trim_test.res b/packages/tests/src/core/S_String_trim_test.res index 1f2c2338..61f8132f 100644 --- a/packages/tests/src/core/S_String_trim_test.res +++ b/packages/tests/src/core/S_String_trim_test.res @@ -1,16 +1,16 @@ open Ava test("Successfully parses", t => { - let struct = S.string->S.String.trim + let schema = S.string->S.String.trim - t->Assert.deepEqual(" Hello world!"->S.parseAnyWith(struct), Ok("Hello world!"), ()) + t->Assert.deepEqual(" Hello world!"->S.parseAnyWith(schema), Ok("Hello world!"), ()) }) test("Successfully serializes", t => { - let struct = S.string->S.String.trim + let schema = S.string->S.String.trim t->Assert.deepEqual( - " Hello world!"->S.serializeToUnknownWith(struct), + " Hello world!"->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) diff --git a/packages/tests/src/core/S_String_url_test.res b/packages/tests/src/core/S_String_url_test.res index b0f24665..abd269ea 100644 --- a/packages/tests/src/core/S_String_url_test.res +++ b/packages/tests/src/core/S_String_url_test.res @@ -1,36 +1,36 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.url + let schema = S.string->S.String.url - t->Assert.deepEqual("http://dzakh.dev"->S.parseAnyWith(struct), Ok("http://dzakh.dev"), ()) + t->Assert.deepEqual("http://dzakh.dev"->S.parseAnyWith(schema), Ok("http://dzakh.dev"), ()) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.url + let schema = S.string->S.String.url t->Assert.deepEqual( - "cifjhdsfhsd"->S.parseAnyWith(struct), + "cifjhdsfhsd"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Invalid url"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.url + let schema = S.string->S.String.url t->Assert.deepEqual( - "http://dzakh.dev"->S.serializeToUnknownWith(struct), + "http://dzakh.dev"->S.serializeToUnknownWith(schema), Ok(%raw(`"http://dzakh.dev"`)), (), ) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.url + let schema = S.string->S.String.url t->Assert.deepEqual( - "cifjhdsfhsd"->S.serializeToUnknownWith(struct), + "cifjhdsfhsd"->S.serializeToUnknownWith(schema), Error( U.error({code: OperationFailed("Invalid url"), operation: Serializing, path: S.Path.empty}), ), @@ -39,10 +39,10 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.string->S.String.url(~message="Custom") + let schema = S.string->S.String.url(~message="Custom") t->Assert.deepEqual( - "abc"->S.parseAnyWith(struct), + "abc"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) diff --git a/packages/tests/src/core/S_String_uuid_test.res b/packages/tests/src/core/S_String_uuid_test.res index 21232f6e..2d7ad37d 100644 --- a/packages/tests/src/core/S_String_uuid_test.res +++ b/packages/tests/src/core/S_String_uuid_test.res @@ -1,40 +1,40 @@ open Ava test("Successfully parses valid data", t => { - let struct = S.string->S.String.uuid + let schema = S.string->S.String.uuid t->Assert.deepEqual( - "123e4567-e89b-12d3-a456-426614174000"->S.parseAnyWith(struct), + "123e4567-e89b-12d3-a456-426614174000"->S.parseAnyWith(schema), Ok("123e4567-e89b-12d3-a456-426614174000"), (), ) }) test("Fails to parse invalid data", t => { - let struct = S.string->S.String.uuid + let schema = S.string->S.String.uuid t->Assert.deepEqual( - "123e4567"->S.parseAnyWith(struct), + "123e4567"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Invalid UUID"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully serializes valid value", t => { - let struct = S.string->S.String.uuid + let schema = S.string->S.String.uuid t->Assert.deepEqual( - "123e4567-e89b-12d3-a456-426614174000"->S.serializeToUnknownWith(struct), + "123e4567-e89b-12d3-a456-426614174000"->S.serializeToUnknownWith(schema), Ok(%raw(`"123e4567-e89b-12d3-a456-426614174000"`)), (), ) }) test("Fails to serialize invalid value", t => { - let struct = S.string->S.String.uuid + let schema = S.string->S.String.uuid t->Assert.deepEqual( - "123e4567"->S.serializeToUnknownWith(struct), + "123e4567"->S.serializeToUnknownWith(schema), Error( U.error({code: OperationFailed("Invalid UUID"), operation: Serializing, path: S.Path.empty}), ), @@ -43,10 +43,10 @@ test("Fails to serialize invalid value", t => { }) test("Returns custom error message", t => { - let struct = S.string->S.String.uuid(~message="Custom") + let schema = S.string->S.String.uuid(~message="Custom") t->Assert.deepEqual( - "abc"->S.parseAnyWith(struct), + "abc"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("Custom"), operation: Parsing, path: S.Path.empty})), (), ) diff --git a/packages/tests/src/core/S_array_test.res b/packages/tests/src/core/S_array_test.res index 0750b73e..a04aa901 100644 --- a/packages/tests/src/core/S_array_test.res +++ b/packages/tests/src/core/S_array_test.res @@ -9,19 +9,19 @@ module CommonWithNested = { let factory = () => S.array(S.string) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -31,10 +31,10 @@ module CommonWithNested = { }) test("Fails to parse nested", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - nestedInvalidAny->S.parseAnyWith(struct), + nestedInvalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: 1->Obj.magic}), @@ -47,43 +47,43 @@ module CommonWithNested = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v1;if(!Array.isArray(i)){e[1](i)}v1=[];for(let v0=0;v0 { - let struct = S.array(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) + let schema = S.array(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v1,v5;if(!Array.isArray(i)){e[1](i)}v1=[];for(let v0=0;v0{try{return v3().catch(v2=>{if(v2&&v2.s===s){v2.path=""+'["'+v0+'"]'+v2.path}throw v2})}catch(v2){if(v2&&v2.s===s){v2.path=""+'["'+v0+'"]'+v2.path}throw v2}};}catch(v2){if(v2&&v2.s===s){v2.path=""+'["'+v0+'"]'+v2.path}throw v2}v1.push(v4)}v5=()=>Promise.all(v1.map(t=>t()));return v5}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.array(S.string) + let schema = S.array(S.string) - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) test("Compiled serialize code snapshot with transform", t => { - let struct = S.array(S.option(S.string)) + let schema = S.array(S.option(S.string)) // TODO: Simplify t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v1;v1=[];for(let v0=0;v0 { - let struct = S.array(S.array(S.string)) + let schema = S.array(S.array(S.string)) t->Assert.deepEqual( - %raw(`[["a", "b"], ["c", "d"]]`)->S.parseAnyWith(struct), + %raw(`[["a", "b"], ["c", "d"]]`)->S.parseAnyWith(schema), Ok([["a", "b"], ["c", "d"]]), (), ) }) test("Fails to parse matrix", t => { - let struct = S.array(S.array(S.string)) + let schema = S.array(S.array(S.string)) t->Assert.deepEqual( - %raw(`[["a", 1], ["c", "d"]]`)->S.parseAnyWith(struct), + %raw(`[["a", 1], ["c", "d"]]`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: %raw(`1`)}), @@ -117,10 +117,10 @@ test("Fails to parse matrix", t => { }) test("Successfully parses array of optional items", t => { - let struct = S.array(S.option(S.string)) + let schema = S.array(S.option(S.string)) t->Assert.deepEqual( - %raw(`["a", undefined, undefined, "b"]`)->S.parseAnyWith(struct), + %raw(`["a", undefined, undefined, "b"]`)->S.parseAnyWith(schema), Ok([Some("a"), None, None, Some("b")]), (), ) diff --git a/packages/tests/src/core/S_bool_test.res b/packages/tests/src/core/S_bool_test.res index 68306b6d..b7184e42 100644 --- a/packages/tests/src/core/S_bool_test.res +++ b/packages/tests/src/core/S_bool_test.res @@ -8,19 +8,19 @@ module Common = { let factory = () => S.bool test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse ", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -30,32 +30,32 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{if(typeof i!=="boolean"){e[0](i)}return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{if(typeof i!=="boolean"){e[0](i)}return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) } test("Parses bool when JSON is true", t => { - let struct = S.bool + let schema = S.bool - t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(struct), Ok(true), ()) + t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(schema), Ok(true), ()) }) test("Parses bool when JSON is false", t => { - let struct = S.bool + let schema = S.bool - t->Assert.deepEqual(JSON.Encode.bool(false)->S.parseAnyWith(struct), Ok(false), ()) + t->Assert.deepEqual(JSON.Encode.bool(false)->S.parseAnyWith(schema), Ok(false), ()) }) diff --git a/packages/tests/src/core/S_catch_test.res b/packages/tests/src/core/S_catch_test.res index b4f76191..b4a464b8 100644 --- a/packages/tests/src/core/S_catch_test.res +++ b/packages/tests/src/core/S_catch_test.res @@ -2,28 +2,28 @@ open Ava open RescriptCore test("Doesn't affect valid parsing", t => { - let struct = S.string->S.catch(_ => "fallback") + let schema = S.string->S.catch(_ => "fallback") - t->Assert.deepEqual("abc"->S.parseAnyWith(struct), Ok("abc"), ()) + t->Assert.deepEqual("abc"->S.parseAnyWith(schema), Ok("abc"), ()) }) -test("Doesn't do anything with unknown struct", t => { - let struct = S.unknown->S.catch(_ => %raw(`"fallback"`)) +test("Doesn't do anything with unknown schema", t => { + let schema = S.unknown->S.catch(_ => %raw(`"fallback"`)) - t->Assert.deepEqual("abc"->S.parseAnyWith(struct), Ok(%raw(`"abc"`)), ()) + t->Assert.deepEqual("abc"->S.parseAnyWith(schema), Ok(%raw(`"abc"`)), ()) }) test("Uses fallback value when parsing failed", t => { - let struct = S.string->S.catch(_ => "fallback") + let schema = S.string->S.catch(_ => "fallback") - t->Assert.deepEqual(123->S.parseAnyWith(struct), Ok("fallback"), ()) + t->Assert.deepEqual(123->S.parseAnyWith(schema), Ok("fallback"), ()) }) test("Doesn't affect serializing in any way", t => { - let struct = S.literal("123")->S.catch(_ => "fallback") + let schema = S.literal("123")->S.catch(_ => "fallback") t->Assert.deepEqual( - "abc"->S.serializeToUnknownWith(struct), + "abc"->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({received: "abc"->Obj.magic, expected: String("123")}), @@ -37,7 +37,7 @@ test("Doesn't affect serializing in any way", t => { test("Provides ctx to use in catch", t => { t->ExecutionContext.plan(3) - let struct = S.string->S.catch(s => { + let schema = S.string->S.catch(s => { t->Assert.deepEqual( s.error, U.error({ @@ -51,21 +51,21 @@ test("Provides ctx to use in catch", t => { "fallback" }) - t->Assert.deepEqual(123->S.parseAnyWith(struct), Ok("fallback"), ()) + t->Assert.deepEqual(123->S.parseAnyWith(schema), Ok("fallback"), ()) }) test("Can use s.fail inside of S.catch", t => { - let struct = S.literal("0")->S.catch(s => { + let schema = S.literal("0")->S.catch(s => { switch s.input->S.parseAnyWith(S.string) { | Ok(_) => "1" | Error(_) => s.fail("Fallback value only supported for strings.") } }) - t->Assert.deepEqual("0"->S.parseAnyWith(struct), Ok("0"), ()) - t->Assert.deepEqual("abc"->S.parseAnyWith(struct), Ok("1"), ()) + t->Assert.deepEqual("0"->S.parseAnyWith(schema), Ok("0"), ()) + t->Assert.deepEqual("abc"->S.parseAnyWith(schema), Ok("1"), ()) t->Assert.deepEqual( - 123->S.parseAnyWith(struct), + 123->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Fallback value only supported for strings."), @@ -75,9 +75,9 @@ test("Can use s.fail inside of S.catch", t => { ), (), ) - t->Assert.deepEqual("0"->S.serializeToUnknownWith(struct), Ok(%raw(`"0"`)), ()) + t->Assert.deepEqual("0"->S.serializeToUnknownWith(schema), Ok(%raw(`"0"`)), ()) t->Assert.deepEqual( - "1"->S.serializeToUnknownWith(struct), + "1"->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: String("0"), received: "1"->Obj.magic}), @@ -89,59 +89,59 @@ test("Can use s.fail inside of S.catch", t => { ) }) -asyncTest("Uses fallback value when async struct parsing failed during the sync part", async t => { - let struct = +asyncTest("Uses fallback value when async schema parsing failed during the sync part", async t => { + let schema = S.string ->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)}) ->S.catch(_ => "fallback") - t->Assert.deepEqual(await 123->S.parseAnyAsyncWith(struct), Ok("fallback"), ()) + t->Assert.deepEqual(await 123->S.parseAnyAsyncWith(schema), Ok("fallback"), ()) }) -asyncTest("Uses fallback value when async struct parsing failed during the async part", async t => { - let struct = +asyncTest("Uses fallback value when async schema parsing failed during the async part", async t => { + let schema = S.string->S.transform(s => {asyncParser: _ => s.fail("foo")})->S.catch(_ => "fallback") - t->Assert.deepEqual(await "123"->S.parseAnyAsyncWith(struct), Ok("fallback"), ()) + t->Assert.deepEqual(await "123"->S.parseAnyAsyncWith(schema), Ok("fallback"), ()) }) asyncTest( - "Uses fallback value when async struct parsing failed during the async part in promise", + "Uses fallback value when async schema parsing failed during the async part in promise", async t => { - let struct = + let schema = S.string ->S.transform(s => { asyncParser: _ => () => Promise.resolve()->Promise.thenResolve(() => s.fail("fail")), }) ->S.catch(_ => "fallback") - t->Assert.deepEqual(await "123"->S.parseAnyAsyncWith(struct), Ok("fallback"), ()) + t->Assert.deepEqual(await "123"->S.parseAnyAsyncWith(schema), Ok("fallback"), ()) }, ) test("Compiled parse code snapshot", t => { - let struct = S.bool->S.catch(_ => false) + let schema = S.bool->S.catch(_ => false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{try{if(typeof i!=="boolean"){e[1](i)}}catch(v0){if(v0&&v0.s===s){i=e[0](i,v0)}else{throw v0}}return i}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = + let schema = S.bool->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})->S.catch(_ => false) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v1,v2;try{if(typeof i!=="boolean"){e[1](i)}v1=e[2](i);v2=()=>{try{return v1().catch(v0=>{if(v0&&v0.s===s){return e[0](i,v0)}else{throw v0}})}catch(v0){if(v0&&v0.s===s){return Promise.resolve(e[0](i,v0))}else{throw v0}}};}catch(v0){if(v0&&v0.s===s){v2=()=>Promise.resolve(e[0](i,v0))}else{throw v0}}return v2}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.bool->S.catch(_ => false) + let schema = S.bool->S.catch(_ => false) - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) diff --git a/packages/tests/src/core/S_custom_test.res b/packages/tests/src/core/S_custom_test.res index 69d0eb87..4bb5e6d6 100644 --- a/packages/tests/src/core/S_custom_test.res +++ b/packages/tests/src/core/S_custom_test.res @@ -1,13 +1,13 @@ open Ava open RescriptCore -let nullableStruct = innerStruct => { +let nullableSchema = innerSchema => { S.custom("Nullable", s => { parser: unknown => { if unknown === %raw(`undefined`) || unknown === %raw(`null`) { None } else { - switch unknown->S.parseAnyWith(innerStruct) { + switch unknown->S.parseAnyWith(innerSchema) { | Ok(value) => Some(value) | Error(error) => s.failWithError(error) } @@ -16,7 +16,7 @@ let nullableStruct = innerStruct => { serializer: value => { switch value { | Some(innerValue) => - switch innerValue->S.serializeToUnknownWith(innerStruct) { + switch innerValue->S.serializeToUnknownWith(innerSchema) { | Ok(value) => value | Error(error) => s.failWithError(error) } @@ -26,14 +26,14 @@ let nullableStruct = innerStruct => { }) } -test("Correctly parses custom struct", t => { - let struct = nullableStruct(S.string) +test("Correctly parses custom schema", t => { + let schema = nullableSchema(S.string) - t->Assert.deepEqual("Hello world!"->S.parseAnyWith(struct), Ok(Some("Hello world!")), ()) - t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(struct), Ok(None), ()) - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok(None), ()) + t->Assert.deepEqual("Hello world!"->S.parseAnyWith(schema), Ok(Some("Hello world!")), ()) + t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(schema), Ok(None), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok(None), ()) t->Assert.deepEqual( - 123->S.parseAnyWith(struct), + 123->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: %raw(`123`)}), @@ -45,24 +45,24 @@ test("Correctly parses custom struct", t => { ) }) -test("Correctly serializes custom struct", t => { - let struct = nullableStruct(S.string) +test("Correctly serializes custom schema", t => { + let schema = nullableSchema(S.string) t->Assert.deepEqual( - Some("Hello world!")->S.serializeToUnknownWith(struct), + Some("Hello world!")->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) - t->Assert.deepEqual(None->S.serializeToUnknownWith(struct), Ok(%raw(`null`)), ()) + t->Assert.deepEqual(None->S.serializeToUnknownWith(schema), Ok(%raw(`null`)), ()) }) test("Fails to serialize with user error", t => { - let struct = S.custom("Test", s => { + let schema = S.custom("Test", s => { serializer: _ => s.fail("User error"), }) t->Assert.deepEqual( - None->S.serializeToUnknownWith(struct), + None->S.serializeToUnknownWith(schema), Error( U.error({code: OperationFailed("User error"), operation: Serializing, path: S.Path.empty}), ), @@ -71,12 +71,12 @@ test("Fails to serialize with user error", t => { }) test("Fails to serialize with serializer is missing", t => { - let struct = S.custom("Test", _ => { + let schema = S.custom("Test", _ => { parser: _ => (), }) t->Assert.deepEqual( - ()->S.serializeToUnknownWith(struct), + ()->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({description: "The S.custom serializer is missing"}), @@ -89,9 +89,9 @@ test("Fails to serialize with serializer is missing", t => { }) asyncTest("Parses with asyncParser", async t => { - let struct = S.custom("Test", _ => { + let schema = S.custom("Test", _ => { asyncParser: _ => () => Promise.resolve(), }) - t->Assert.deepEqual(await %raw(`undefined`)->S.parseAnyAsyncWith(struct), Ok(), ()) + t->Assert.deepEqual(await %raw(`undefined`)->S.parseAnyAsyncWith(schema), Ok(), ()) }) diff --git a/packages/tests/src/core/S_deprecate_test.res b/packages/tests/src/core/S_deprecate_test.res index 9bb617b1..a16980e5 100644 --- a/packages/tests/src/core/S_deprecate_test.res +++ b/packages/tests/src/core/S_deprecate_test.res @@ -8,19 +8,19 @@ module Common = { let factory = () => S.string->S.option->S.deprecate("Some warning") test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -30,32 +30,32 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) } test("Successfully parses primitive", t => { - let struct = S.bool->S.option->S.deprecate("Deprecated") + let schema = S.bool->S.option->S.deprecate("Deprecated") - t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(struct), Ok(Some(true)), ()) + t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(schema), Ok(Some(true)), ()) }) test("Successfully parses undefined", t => { - let struct = S.bool->S.option->S.deprecate("Deprecated") + let schema = S.bool->S.option->S.deprecate("Deprecated") - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok(None), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok(None), ()) }) test("Fails to parse null", t => { - let struct = S.bool->S.option->S.deprecate("Deprecated") + let schema = S.bool->S.option->S.deprecate("Deprecated") t->Assert.deepEqual( - %raw(`null`)->S.parseAnyWith(struct), + %raw(`null`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`null`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`null`)}), operation: Parsing, path: S.Path.empty, }), @@ -64,8 +64,8 @@ test("Fails to parse null", t => { ) }) -test("Successfully parses null for deprecated nullable struct", t => { - let struct = S.null(S.bool)->S.option->S.deprecate("Deprecated") +test("Successfully parses null for deprecated nullable schema", t => { + let schema = S.null(S.bool)->S.option->S.deprecate("Deprecated") - t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(struct), Ok(None), ()) + t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(schema), Ok(None), ()) }) diff --git a/packages/tests/src/core/S_description_test.res b/packages/tests/src/core/S_description_test.res index 20356a48..0d8fae7f 100644 --- a/packages/tests/src/core/S_description_test.res +++ b/packages/tests/src/core/S_description_test.res @@ -1,27 +1,27 @@ open Ava -test("S.description returns None for not described structs", t => { - let struct = S.string +test("S.description returns None for not described schemas", t => { + let schema = S.string - t->Assert.deepEqual(struct->S.description, None, ()) + t->Assert.deepEqual(schema->S.description, None, ()) }) -test("S.description returns Some for described structs", t => { - let struct = S.string->S.describe("A useful bit of text, if you know what to do with it.") +test("S.description returns Some for described schemas", t => { + let schema = S.string->S.describe("A useful bit of text, if you know what to do with it.") t->Assert.deepEqual( - struct->S.description, + schema->S.description, Some("A useful bit of text, if you know what to do with it."), (), ) }) test("Transforms don't remove description", t => { - let struct = + let schema = S.string->S.describe("A useful bit of text, if you know what to do with it.")->S.String.trim t->Assert.deepEqual( - struct->S.description, + schema->S.description, Some("A useful bit of text, if you know what to do with it."), (), ) diff --git a/packages/tests/src/core/S_dict_test.res b/packages/tests/src/core/S_dict_test.res index 0afaed4e..019e78e3 100644 --- a/packages/tests/src/core/S_dict_test.res +++ b/packages/tests/src/core/S_dict_test.res @@ -9,25 +9,25 @@ module CommonWithNested = { let factory = () => S.dict(S.string) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -37,10 +37,10 @@ module CommonWithNested = { }) test("Fails to parse nested", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - nestedInvalidAny->S.parseAnyWith(struct), + nestedInvalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: %raw(`true`)}), @@ -53,36 +53,36 @@ module CommonWithNested = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v1;if(!i||i.constructor!==Object){e[1](i)}v1={};for(let v0 in i){let v3;try{v3=i[v0];if(typeof v3!=="string"){e[0](v3)}}catch(v2){if(v2&&v2.s===s){v2.path=""+'["'+v0+'"]'+v2.path}throw v2}v1[v0]=v3}return v1}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = S.dict(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) + let schema = S.dict(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v1,v9;if(!i||i.constructor!==Object){e[1](i)}v1={};for(let v0 in i){let v3,v4;try{v3=e[0](i[v0]);v4=()=>{try{return v3().catch(v2=>{if(v2&&v2.s===s){v2.path=""+'["'+v0+'"]'+v2.path}throw v2})}catch(v2){if(v2&&v2.s===s){v2.path=""+'["'+v0+'"]'+v2.path}throw v2}};}catch(v2){if(v2&&v2.s===s){v2.path=""+'["'+v0+'"]'+v2.path}throw v2}v1[v0]=v4}v9=()=>new Promise((v5,v6)=>{let v8=Object.keys(v1).length;for(let v0 in v1){v1[v0]().then(v7=>{v1[v0]=v7;if(v8--===1){v5(v1)}},v6)}});return v9}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.dict(S.string) + let schema = S.dict(S.string) - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) test("Compiled serialize code snapshot with transform", t => { - let struct = S.dict(S.option(S.string)) + let schema = S.dict(S.option(S.string)) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v1;v1={};for(let v0 in i){let v3,v4;try{v3=i[v0];if(v3!==void 0){v4=e[0](v3)}else{v4=void 0}}catch(v2){if(v2&&v2.s===s){v2.path=""+\'["\'+v0+\'"]\'+v2.path}throw v2}v1[v0]=v4}return v1}`, ) @@ -90,20 +90,20 @@ module CommonWithNested = { } test("Successfully parses dict with int keys", t => { - let struct = S.dict(S.string) + let schema = S.dict(S.string) t->Assert.deepEqual( - %raw(`{1:"b",2:"d"}`)->S.parseAnyWith(struct), + %raw(`{1:"b",2:"d"}`)->S.parseAnyWith(schema), Ok(Dict.fromArray([("1", "b"), ("2", "d")])), (), ) }) test("Applies operation for each item on serializing", t => { - let struct = S.dict(S.jsonString(S.int)) + let schema = S.dict(S.jsonString(S.int)) t->Assert.deepEqual( - Dict.fromArray([("a", 1), ("b", 2)])->S.serializeToUnknownWith(struct), + Dict.fromArray([("a", 1), ("b", 2)])->S.serializeToUnknownWith(schema), Ok( %raw(`{ "a": "1", @@ -115,10 +115,10 @@ test("Applies operation for each item on serializing", t => { }) test("Fails to serialize dict item", t => { - let struct = S.dict(S.string->S.refine(s => _ => s.fail("User error"))) + let schema = S.dict(S.string->S.refine(s => _ => s.fail("User error"))) t->Assert.deepEqual( - Dict.fromArray([("a", "aa"), ("b", "bb")])->S.serializeToUnknownWith(struct), + Dict.fromArray([("a", "aa"), ("b", "bb")])->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -131,10 +131,10 @@ test("Fails to serialize dict item", t => { }) test("Successfully parses dict with optional items", t => { - let struct = S.dict(S.option(S.string)) + let schema = S.dict(S.option(S.string)) t->Assert.deepEqual( - %raw(`{"key1":"value1","key2":undefined}`)->S.parseAnyWith(struct), + %raw(`{"key1":"value1","key2":undefined}`)->S.parseAnyWith(schema), Ok(Dict.fromArray([("key1", Some("value1")), ("key2", None)])), (), ) diff --git a/packages/tests/src/core/S_failWithError_test.res b/packages/tests/src/core/S_failWithError_test.res index a1d798b8..646ddfe6 100644 --- a/packages/tests/src/core/S_failWithError_test.res +++ b/packages/tests/src/core/S_failWithError_test.res @@ -1,7 +1,7 @@ open Ava test("FIXME: Should keep operation of the error passed to advanced fail", t => { - let struct = S.array( + let schema = S.array( S.string->S.transform(s => { parser: _ => s.failWithError( @@ -15,7 +15,7 @@ test("FIXME: Should keep operation of the error passed to advanced fail", t => { ) t->Assert.deepEqual( - ["Hello world!"]->S.parseAnyWith(struct), + ["Hello world!"]->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -28,7 +28,7 @@ test("FIXME: Should keep operation of the error passed to advanced fail", t => { }) test("Works with failing outside of the parser", t => { - let struct = S.object(s => + let schema = S.object(s => s.field( "root", S.array( @@ -47,7 +47,7 @@ test("Works with failing outside of the parser", t => { ) t->Assert.deepEqual( - ["Hello world!"]->S.parseAnyWith(struct), + ["Hello world!"]->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("User error"), diff --git a/packages/tests/src/core/S_float_test.res b/packages/tests/src/core/S_float_test.res index ceb3e6ba..06519d44 100644 --- a/packages/tests/src/core/S_float_test.res +++ b/packages/tests/src/core/S_float_test.res @@ -7,19 +7,19 @@ module Common = { let factory = () => S.float test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -29,42 +29,42 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{if(typeof i!=="number"||Number.isNaN(i)){e[0](i)}return i}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) } test("Successfully parses number with a fractional part", t => { - let struct = S.float + let schema = S.float - t->Assert.deepEqual(%raw(`123.123`)->S.parseAnyWith(struct), Ok(123.123), ()) + t->Assert.deepEqual(%raw(`123.123`)->S.parseAnyWith(schema), Ok(123.123), ()) }) test("Fails to parse NaN", t => { - let struct = S.float + let schema = S.float t->Assert.deepEqual( - %raw(`NaN`)->S.parseAnyWith(struct), + %raw(`NaN`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`NaN`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`NaN`)}), operation: Parsing, path: S.Path.empty, }), diff --git a/packages/tests/src/core/S_inline_test.res b/packages/tests/src/core/S_inline_test.res index b30f94d6..f42aa7fa 100644 --- a/packages/tests/src/core/S_inline_test.res +++ b/packages/tests/src/core/S_inline_test.res @@ -1,445 +1,445 @@ open Ava test("Supports String", t => { - let struct = S.string - t->Assert.deepEqual(struct->S.inline, `S.string`, ()) + let schema = S.string + t->Assert.deepEqual(schema->S.inline, `S.string`, ()) }) test("Doesn't support transforms and refinements", t => { - let struct = S.string->S.transform(_ => {parser: ignore})->S.refine(_ => ignore) - t->Assert.deepEqual(struct->S.inline, `S.string`, ()) + let schema = S.string->S.transform(_ => {parser: ignore})->S.refine(_ => ignore) + t->Assert.deepEqual(schema->S.inline, `S.string`, ()) }) test("Supports built-in String.email refinement", t => { - let struct = S.string->S.String.email - let structInlineResult = S.string->S.String.email(~message="Invalid email address") + let schema = S.string->S.String.email + let schemaInlineResult = S.string->S.String.email(~message="Invalid email address") - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.string->S.String.email(~message="Invalid email address")`, (), ) }) test("Supports built-in String.datetime refinement", t => { - let struct = S.string->S.String.datetime - let structInlineResult = + let schema = S.string->S.String.datetime + let schemaInlineResult = S.string->S.String.datetime(~message="Invalid datetime string! Must be UTC") - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.string->S.String.datetime(~message="Invalid datetime string! Must be UTC")`, (), ) }) test("Supports built-in String.url refinement", t => { - let struct = S.string->S.String.url - let structInlineResult = S.string->S.String.url(~message="Invalid url") + let schema = S.string->S.String.url + let schemaInlineResult = S.string->S.String.url(~message="Invalid url") - t->U.assertEqualStructs(struct, structInlineResult) - t->Assert.deepEqual(struct->S.inline, `S.string->S.String.url(~message="Invalid url")`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult) + t->Assert.deepEqual(schema->S.inline, `S.string->S.String.url(~message="Invalid url")`, ()) }) test("Supports built-in String.uuid refinement", t => { - let struct = S.string->S.String.uuid - let structInlineResult = S.string->S.String.uuid(~message="Invalid UUID") + let schema = S.string->S.String.uuid + let schemaInlineResult = S.string->S.String.uuid(~message="Invalid UUID") - t->U.assertEqualStructs(struct, structInlineResult) - t->Assert.deepEqual(struct->S.inline, `S.string->S.String.uuid(~message="Invalid UUID")`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult) + t->Assert.deepEqual(schema->S.inline, `S.string->S.String.uuid(~message="Invalid UUID")`, ()) }) test("Supports built-in String.cuid refinement", t => { - let struct = S.string->S.String.cuid - let structInlineResult = S.string->S.String.cuid(~message="Invalid CUID") + let schema = S.string->S.String.cuid + let schemaInlineResult = S.string->S.String.cuid(~message="Invalid CUID") - t->U.assertEqualStructs(struct, structInlineResult) - t->Assert.deepEqual(struct->S.inline, `S.string->S.String.cuid(~message="Invalid CUID")`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult) + t->Assert.deepEqual(schema->S.inline, `S.string->S.String.cuid(~message="Invalid CUID")`, ()) }) test("Supports built-in String.min refinement", t => { - let struct = S.string->S.String.min(5) - let structInlineResult = + let schema = S.string->S.String.min(5) + let schemaInlineResult = S.string->S.String.min(5, ~message="String must be 5 or more characters long") - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.string->S.String.min(5, ~message="String must be 5 or more characters long")`, (), ) }) test("Supports built-in String.max refinement", t => { - let struct = S.string->S.String.max(5) - let structInlineResult = + let schema = S.string->S.String.max(5) + let schemaInlineResult = S.string->S.String.max(5, ~message="String must be 5 or fewer characters long") - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.string->S.String.max(5, ~message="String must be 5 or fewer characters long")`, (), ) }) test("Supports built-in String.length refinement", t => { - let struct = S.string->S.String.length(5) - let structInlineResult = + let schema = S.string->S.String.length(5) + let schemaInlineResult = S.string->S.String.length(~message="String must be exactly 5 characters long", 5) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.string->S.String.length(5, ~message="String must be exactly 5 characters long")`, (), ) }) test("Supports built-in String.pattern refinement", t => { - let struct = S.string->S.String.pattern(%re("/0-9/")) - let structInlineResult = S.string->S.String.pattern(~message="Invalid", %re("/0-9/")) + let schema = S.string->S.String.pattern(%re("/0-9/")) + let schemaInlineResult = S.string->S.String.pattern(~message="Invalid", %re("/0-9/")) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.string->S.String.pattern(%re("/0-9/"), ~message="Invalid")`, (), ) }) test("Supports Int", t => { - let struct = S.int - t->Assert.deepEqual(struct->S.inline, `S.int`, ()) + let schema = S.int + t->Assert.deepEqual(schema->S.inline, `S.int`, ()) }) test("Supports built-in Int.max refinement", t => { - let struct = S.int->S.Int.max(4) - let structInlineResult = S.int->S.Int.max(~message="Number must be lower than or equal to 4", 4) + let schema = S.int->S.Int.max(4) + let schemaInlineResult = S.int->S.Int.max(~message="Number must be lower than or equal to 4", 4) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.int->S.Int.max(4, ~message="Number must be lower than or equal to 4")`, (), ) }) test("Supports built-in Int.min refinement", t => { - let struct = S.int->S.Int.min(4) - let structInlineResult = S.int->S.Int.min(4, ~message="Number must be greater than or equal to 4") + let schema = S.int->S.Int.min(4) + let schemaInlineResult = S.int->S.Int.min(4, ~message="Number must be greater than or equal to 4") - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.int->S.Int.min(4, ~message="Number must be greater than or equal to 4")`, (), ) }) test("Supports built-in Int.port refinement", t => { - let struct = S.int->S.Int.port - let structInlineResult = S.int->S.Int.port(~message="Invalid port") + let schema = S.int->S.Int.port + let schemaInlineResult = S.int->S.Int.port(~message="Invalid port") - t->U.assertEqualStructs(struct, structInlineResult) - t->Assert.deepEqual(struct->S.inline, `S.int->S.Int.port(~message="Invalid port")`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult) + t->Assert.deepEqual(schema->S.inline, `S.int->S.Int.port(~message="Invalid port")`, ()) }) test("Supports Float", t => { - let struct = S.float - t->Assert.deepEqual(struct->S.inline, `S.float`, ()) + let schema = S.float + t->Assert.deepEqual(schema->S.inline, `S.float`, ()) }) test("Supports built-in Float.max refinement", t => { - let struct = S.float->S.Float.max(4.) - let structInlineResult = + let schema = S.float->S.Float.max(4.) + let schemaInlineResult = S.float->S.Float.max(~message="Number must be lower than or equal to 4", 4.) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.float->S.Float.max(4., ~message="Number must be lower than or equal to 4")`, (), ) }) test("Supports built-in Float.max refinement with digits after decimal point", t => { - let struct = S.float->S.Float.max(4.4) - let structInlineResult = + let schema = S.float->S.Float.max(4.4) + let schemaInlineResult = S.float->S.Float.max(~message="Number must be lower than or equal to 4.4", 4.4) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.float->S.Float.max(4.4, ~message="Number must be lower than or equal to 4.4")`, (), ) }) test("Supports built-in Float.min refinement", t => { - let struct = S.float->S.Float.min(4.) - let structInlineResult = + let schema = S.float->S.Float.min(4.) + let schemaInlineResult = S.float->S.Float.min(~message="Number must be greater than or equal to 4", 4.) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.float->S.Float.min(4., ~message="Number must be greater than or equal to 4")`, (), ) }) test("Supports built-in Float.min refinement with digits after decimal point", t => { - let struct = S.float->S.Float.min(4.4) - let structInlineResult = + let schema = S.float->S.Float.min(4.4) + let schemaInlineResult = S.float->S.Float.min(~message="Number must be greater than or equal to 4.4", 4.4) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.float->S.Float.min(4.4, ~message="Number must be greater than or equal to 4.4")`, (), ) }) test("Supports multiple built-in refinements", t => { - let struct = S.string->S.String.min(5)->S.String.max(10) - let structInlineResult = + let schema = S.string->S.String.min(5)->S.String.max(10) + let schemaInlineResult = S.string ->S.String.min(~message="String must be 5 or more characters long", 5) ->S.String.max(~message="String must be 10 or fewer characters long", 10) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.string->S.String.min(5, ~message="String must be 5 or more characters long")->S.String.max(10, ~message="String must be 10 or fewer characters long")`, (), ) }) test("Supports Bool", t => { - let struct = S.bool - t->Assert.deepEqual(struct->S.inline, `S.bool`, ()) + let schema = S.bool + t->Assert.deepEqual(schema->S.inline, `S.bool`, ()) }) test("Supports Unknown", t => { - let struct = S.unknown - t->Assert.deepEqual(struct->S.inline, `S.unknown`, ()) + let schema = S.unknown + t->Assert.deepEqual(schema->S.inline, `S.unknown`, ()) }) -test("Treats custom struct factory as Unknown", t => { - let struct = S.custom("Test", s => s.fail("User error")) - t->Assert.deepEqual(struct->S.inline, `S.unknown`, ()) +test("Treats custom schema factory as Unknown", t => { + let schema = S.custom("Test", s => s.fail("User error")) + t->Assert.deepEqual(schema->S.inline, `S.unknown`, ()) }) test("Supports Never", t => { - let struct = S.never - t->Assert.deepEqual(struct->S.inline, `S.never`, ()) + let schema = S.never + t->Assert.deepEqual(schema->S.inline, `S.never`, ()) }) test("Supports JSON", t => { - let struct = S.json - t->Assert.deepEqual(struct->S.inline, `S.json`, ()) + let schema = S.json + t->Assert.deepEqual(schema->S.inline, `S.json`, ()) }) test("Supports String Literal", t => { - let struct = S.literal("foo") - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`"foo"\`))`, ()) + let schema = S.literal("foo") + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`"foo"\`))`, ()) }) test("Escapes the String Literal value", t => { - let struct = S.literal(`"foo"`) - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`"\\"foo\\""\`))`, ()) + let schema = S.literal(`"foo"`) + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`"\\"foo\\""\`))`, ()) }) test("Supports Number Literal like int", t => { - let struct = S.literal(3) - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`3\`))`, ()) + let schema = S.literal(3) + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`3\`))`, ()) }) test("Supports Number Literal", t => { - let struct = S.literal(3.) - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`3\`))`, ()) + let schema = S.literal(3.) + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`3\`))`, ()) }) test("Supports Number Literal with decimal", t => { - let struct = S.literal(3.3) - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`3.3\`))`, ()) + let schema = S.literal(3.3) + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`3.3\`))`, ()) }) test("Supports Boolean Literal", t => { - let struct = S.literal(true) - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`true\`))`, ()) + let schema = S.literal(true) + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`true\`))`, ()) }) test("Supports Undefined Literal", t => { - let struct = S.literal() - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`undefined\`))`, ()) + let schema = S.literal() + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`undefined\`))`, ()) }) test("Supports Null Literal", t => { - let struct = S.literal(%raw(`null`)) - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`null\`))`, ()) + let schema = S.literal(%raw(`null`)) + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`null\`))`, ()) }) test("Supports NaN Literal", t => { - let struct = S.literal(%raw(`NaN`)) - t->Assert.deepEqual(struct->S.inline, `S.literal(%raw(\`NaN\`))`, ()) + let schema = S.literal(%raw(`NaN`)) + t->Assert.deepEqual(schema->S.inline, `S.literal(%raw(\`NaN\`))`, ()) }) test("Supports Option", t => { - let struct = S.option(S.string) - t->Assert.deepEqual(struct->S.inline, `S.option(S.string)`, ()) + let schema = S.option(S.string) + t->Assert.deepEqual(schema->S.inline, `S.option(S.string)`, ()) }) test("Supports Option.getOrWith", t => { - let struct = S.float->S.option->S.Option.getOrWith(() => 4.) + let schema = S.float->S.option->S.Option.getOrWith(() => 4.) let _ = S.float->S.option->S.Option.getOrWith(() => %raw(`4`)) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.option(S.float)->S.Option.getOrWith(() => %raw(\`4\`))`, (), ) }) test("Supports Option.getOr", t => { - let struct = S.float->S.option->S.Option.getOr(4.) + let schema = S.float->S.option->S.Option.getOr(4.) let _ = S.float->S.option->S.Option.getOr(%raw(`4`)) - t->Assert.deepEqual(struct->S.inline, `S.option(S.float)->S.Option.getOr(%raw(\`4\`))`, ()) + t->Assert.deepEqual(schema->S.inline, `S.option(S.float)->S.Option.getOr(%raw(\`4\`))`, ()) }) test("Supports Deprecated with message", t => { - let struct = S.string->S.deprecate("Will be removed in API v2.") - t->Assert.deepEqual(struct->S.inline, `S.string->S.deprecate("Will be removed in API v2.")`, ()) + let schema = S.string->S.deprecate("Will be removed in API v2.") + t->Assert.deepEqual(schema->S.inline, `S.string->S.deprecate("Will be removed in API v2.")`, ()) }) test("Supports Null", t => { - let struct = S.null(S.string) - t->Assert.deepEqual(struct->S.inline, `S.null(S.string)`, ()) + let schema = S.null(S.string) + t->Assert.deepEqual(schema->S.inline, `S.null(S.string)`, ()) }) test("Supports Array", t => { - let struct = S.array(S.string) - t->Assert.deepEqual(struct->S.inline, `S.array(S.string)`, ()) + let schema = S.array(S.string) + t->Assert.deepEqual(schema->S.inline, `S.array(S.string)`, ()) }) test("Supports built-in Array.max refinement", t => { - let struct = S.array(S.string)->S.Array.max(4) - let structInlineResult = + let schema = S.array(S.string)->S.Array.max(4) + let schemaInlineResult = S.array(S.string)->S.Array.max(~message="Array must be 4 or fewer items long", 4) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.array(S.string)->S.Array.max(4, ~message="Array must be 4 or fewer items long")`, (), ) }) test("Supports built-in Array.min refinement", t => { - let struct = S.array(S.string)->S.Array.min(4) - let structInlineResult = + let schema = S.array(S.string)->S.Array.min(4) + let schemaInlineResult = S.array(S.string)->S.Array.min(~message="Array must be 4 or more items long", 4) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.array(S.string)->S.Array.min(4, ~message="Array must be 4 or more items long")`, (), ) }) test("Supports built-in Array.length refinement", t => { - let struct = S.array(S.string)->S.Array.length(4) - let structInlineResult = + let schema = S.array(S.string)->S.Array.length(4) + let schemaInlineResult = S.array(S.string)->S.Array.length(~message="Array must be exactly 4 items long", 4) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.array(S.string)->S.Array.length(4, ~message="Array must be exactly 4 items long")`, (), ) }) test("Supports Dict", t => { - let struct = S.dict(S.string) - t->Assert.deepEqual(struct->S.inline, `S.dict(S.string)`, ()) + let schema = S.dict(S.string) + t->Assert.deepEqual(schema->S.inline, `S.dict(S.string)`, ()) }) test("Supports tuple1", t => { - let struct = S.tuple1(S.string) - let structInlineResult = S.tuple1(S.string) + let schema = S.tuple1(S.string) + let schemaInlineResult = S.tuple1(S.string) - t->U.assertEqualStructs(struct, structInlineResult) - t->Assert.deepEqual(struct->S.inline, `S.tuple1(S.string)`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult) + t->Assert.deepEqual(schema->S.inline, `S.tuple1(S.string)`, ()) }) test("Supports tuple2", t => { - let struct = S.tuple2(S.string, S.int) - let structInlineResult = S.tuple2(S.string, S.int) + let schema = S.tuple2(S.string, S.int) + let schemaInlineResult = S.tuple2(S.string, S.int) - t->U.assertEqualStructs(struct, structInlineResult) - t->Assert.deepEqual(struct->S.inline, `S.tuple2(S.string, S.int)`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult) + t->Assert.deepEqual(schema->S.inline, `S.tuple2(S.string, S.int)`, ()) }) test("Supports tuple3", t => { - let struct = S.tuple3(S.string, S.int, S.bool) - let structInlineResult = S.tuple3(S.string, S.int, S.bool) + let schema = S.tuple3(S.string, S.int, S.bool) + let schemaInlineResult = S.tuple3(S.string, S.int, S.bool) - t->U.assertEqualStructs(struct, structInlineResult) - t->Assert.deepEqual(struct->S.inline, `S.tuple3(S.string, S.int, S.bool)`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult) + t->Assert.deepEqual(schema->S.inline, `S.tuple3(S.string, S.int, S.bool)`, ()) }) test("Supports Tuple with 4 items", t => { - let struct = S.tuple(s => ( + let schema = S.tuple(s => ( s.item(0, S.string), s.item(1, S.int), s.item(2, S.bool), s.item(3, S.string), )) - let structInlineResult = S.tuple(s => ( + let schemaInlineResult = S.tuple(s => ( s.item(0, S.string), s.item(1, S.int), s.item(2, S.bool), s.item(3, S.string), )) - t->U.assertEqualStructs(struct, structInlineResult) + t->U.assertEqualSchemas(schema, schemaInlineResult) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.tuple(s => (s.item(0, S.string), s.item(1, S.int), s.item(2, S.bool), s.item(3, S.string)))`, (), ) }) test("Supports Union", t => { - let struct = S.union([S.literal(#yes), S.literal(#no)]) - let structInlineResult = S.union([ + let schema = S.union([S.literal(#yes), S.literal(#no)]) + let schemaInlineResult = S.union([ S.literal(%raw(`"yes"`))->S.variant(v => #"Literal(\"yes\")"(v)), S.literal(%raw(`"no"`))->S.variant(v => #"Literal(\"no\")"(v)), ]) - structInlineResult->(U.magic: S.t<[> #"Literal(\"yes\")"('a) | #"Literal(\"no\")"('b)]> => unit) + schemaInlineResult->(U.magic: S.t<[> #"Literal(\"yes\")"('a) | #"Literal(\"no\")"('b)]> => unit) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.union([S.literal(%raw(\`"yes"\`))->S.variant(v => #"Literal(\\"yes\\")"(v)), S.literal(%raw(\`"no"\`))->S.variant(v => #"Literal(\\"no\\")"(v))])`, (), ) }) test("Supports description", t => { - let struct = S.string->S.describe("It's a string") - t->Assert.deepEqual(struct->S.inline, `S.string->S.describe("It's a string")`, ()) + let schema = S.string->S.describe("It's a string") + t->Assert.deepEqual(schema->S.inline, `S.string->S.describe("It's a string")`, ()) }) -// test("Uses S.transform for primitive structs inside of union", t => { -// let struct = S.union([ +// test("Uses S.transform for primitive schemas inside of union", t => { +// let schema = S.union([ // S.string->S.variant(v => #String(v)), // S.bool->S.variant(v => #Bool(v)), // S.float->S.variant(v => #Float(v)), @@ -450,20 +450,20 @@ test("Supports description", t => { // ]) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.string->S.variant(v => #"String"(v)), S.bool->S.variant(v => #"Bool"(v)), S.float->S.variant(v => #"Float"(v)), S.int->S.variant(v => #"Int"(v)), S.unknown->S.variant(v => #"Unknown"(v)), S.never->S.variant(v => #"Never"(v)), S.json->S.variant(v => #"JSON"(v))])`, // (), // ) // }) -// test("Adds index for the same structs inside of the union", t => { -// let struct = S.union([S.string, S.string]) -// let structInlineResult = S.union([ +// test("Adds index for the same schemas inside of the union", t => { +// let schema = S.union([S.string, S.string]) +// let schemaInlineResult = S.union([ // S.string->S.variant(v => #String(v)), // S.string->S.variant(v => #String2(v)), // ]) -// structInlineResult->( +// schemaInlineResult->( // U.magic: S.t< // [ // | #String(string) @@ -473,14 +473,14 @@ test("Supports description", t => { // ) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.string->S.variant(v => #"String"(v)), S.string->S.variant(v => #"String2"(v))])`, // (), // ) // }) test("Supports Object (ignores transformations)", t => { - let struct = S.object(s => + let schema = S.object(s => { "name": s.field("Name", S.string), "email": s.field("Email", S.string), @@ -488,7 +488,7 @@ test("Supports Object (ignores transformations)", t => { } ) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.object(s => { "Name": s.field("Name", S.string), @@ -501,63 +501,63 @@ test("Supports Object (ignores transformations)", t => { }) test("Supports Object.strip", t => { - let struct = S.object(_ => ())->S.Object.strip - t->Assert.deepEqual(struct->S.inline, `S.object(_ => ())`, ()) + let schema = S.object(_ => ())->S.Object.strip + t->Assert.deepEqual(schema->S.inline, `S.object(_ => ())`, ()) }) test("Supports Object.strict", t => { - let struct = S.object(_ => ())->S.Object.strict - t->Assert.deepEqual(struct->S.inline, `S.object(_ => ())->S.Object.strict`, ()) + let schema = S.object(_ => ())->S.Object.strict + t->Assert.deepEqual(schema->S.inline, `S.object(_ => ())->S.Object.strict`, ()) }) test("Supports empty Object (ignores transformations)", t => { - let struct = S.object(_ => 123) - let structInlineResult = S.object(_ => ()) + let schema = S.object(_ => 123) + let schemaInlineResult = S.object(_ => ()) - t->U.assertEqualStructs(struct, structInlineResult->(U.magic: S.t => S.t)) - t->Assert.deepEqual(struct->S.inline, `S.object(_ => ())`, ()) + t->U.assertEqualSchemas(schema, schemaInlineResult->(U.magic: S.t => S.t)) + t->Assert.deepEqual(schema->S.inline, `S.object(_ => ())`, ()) }) test("Supports empty Object in union", t => { - let struct = S.union([S.object(_ => ()), S.object(_ => ())]) - let structInlineResult = S.union([ + let schema = S.union([S.object(_ => ()), S.object(_ => ())]) + let schemaInlineResult = S.union([ S.object(_ => ())->S.variant(v => #"Object({})"(v)), S.object(_ => ())->S.variant(v => #"Object({})2"(v)), ]) - structInlineResult->(U.magic: S.t<[#"Object({})"(unit) | #"Object({})2"(unit)]> => unit) + schemaInlineResult->(U.magic: S.t<[#"Object({})"(unit) | #"Object({})2"(unit)]> => unit) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.union([S.object(_ => ())->S.variant(v => #"Object({})"(v)), S.object(_ => ())->S.variant(v => #"Object({})2"(v))])`, (), ) }) test("Supports Tuple in union", t => { - let struct = S.union([S.tuple1(S.string), S.tuple1(S.string)]) - let structInlineResult = S.union([ + let schema = S.union([S.tuple1(S.string), S.tuple1(S.string)]) + let schemaInlineResult = S.union([ S.tuple1(S.string)->S.variant(v => #"Tuple(String)"(v)), S.tuple1(S.string)->S.variant(v => #"Tuple(String)2"(v)), ]) - structInlineResult->(U.magic: S.t<[#"Tuple(String)"(string) | #"Tuple(String)2"(string)]> => unit) + schemaInlineResult->(U.magic: S.t<[#"Tuple(String)"(string) | #"Tuple(String)2"(string)]> => unit) t->Assert.deepEqual( - struct->S.inline, + schema->S.inline, `S.union([S.tuple1(S.string)->S.variant(v => #"Tuple(String)"(v)), S.tuple1(S.string)->S.variant(v => #"Tuple(String)2"(v))])`, (), ) }) -// test("Supports Option structs in union", t => { -// let struct = S.union([S.option(S.literalVariant(String("123"), 123.)), S.option(S.float)]) -// let structInlineResult = S.union([ +// test("Supports Option schemas in union", t => { +// let schema = S.union([S.option(S.literalVariant(String("123"), 123.)), S.option(S.float)]) +// let schemaInlineResult = S.union([ // S.option(S.literal(String("123")))->S.variant(v => #OptionOf123(v)), // S.option(S.float)->S.variant(v => #OptionOfFloat(v)), // ]) -// structInlineResult->( +// schemaInlineResult->( // U.magic: S.t< // [ // | #OptionOf123(option) @@ -567,20 +567,20 @@ test("Supports Tuple in union", t => { // ) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.option(S.literal(String("123")))->S.variant(v => #"OptionOf123"(v)), S.option(S.float)->S.variant(v => #"OptionOfFloat"(v))])`, // (), // ) // }) -// test("Supports Null structs in union", t => { -// let struct = S.union([S.null(S.literalVariant(String("123"), 123.)), S.null(S.float)]) -// let structInlineResult = S.union([ +// test("Supports Null schemas in union", t => { +// let schema = S.union([S.null(S.literalVariant(String("123"), 123.)), S.null(S.float)]) +// let schemaInlineResult = S.union([ // S.null(S.literal(String("123")))->S.variant(v => #NullOf123(v)), // S.null(S.float)->S.variant(v => #NullOfFloat(v)), // ]) -// structInlineResult->( +// schemaInlineResult->( // U.magic: S.t< // [ // | #NullOf123(option) @@ -590,20 +590,20 @@ test("Supports Tuple in union", t => { // ) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.null(S.literal(String("123")))->S.variant(v => #"NullOf123"(v)), S.null(S.float)->S.variant(v => #"NullOfFloat"(v))])`, // (), // ) // }) -// test("Supports Array structs in union", t => { -// let struct = S.union([S.array(S.literalVariant(String("123"), 123.)), S.array(S.float)]) -// let structInlineResult = S.union([ +// test("Supports Array schemas in union", t => { +// let schema = S.union([S.array(S.literalVariant(String("123"), 123.)), S.array(S.float)]) +// let schemaInlineResult = S.union([ // S.array(S.literal(String("123")))->S.variant(v => #ArrayOf123(v)), // S.array(S.float)->S.variant(v => #ArrayOfFloat(v)), // ]) -// structInlineResult->( +// schemaInlineResult->( // U.magic: S.t< // [ // | #ArrayOf123(array) @@ -613,20 +613,20 @@ test("Supports Tuple in union", t => { // ) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.array(S.literal(String("123")))->S.variant(v => #"ArrayOf123"(v)), S.array(S.float)->S.variant(v => #"ArrayOfFloat"(v))])`, // (), // ) // }) -// test("Supports Dict structs in union", t => { -// let struct = S.union([S.dict(S.literalVariant(String("123"), 123.)), S.dict(S.float)]) -// let structInlineResult = S.union([ +// test("Supports Dict schemas in union", t => { +// let schema = S.union([S.dict(S.literalVariant(String("123"), 123.)), S.dict(S.float)]) +// let schemaInlineResult = S.union([ // S.dict(S.literal(String("123")))->S.variant(v => #DictOf123(v)), // S.dict(S.float)->S.variant(v => #DictOfFloat(v)), // ]) -// structInlineResult->( +// schemaInlineResult->( // U.magic: S.t< // [ // | #DictOf123(Dict.t) @@ -636,18 +636,18 @@ test("Supports Tuple in union", t => { // ) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.dict(S.literal(String("123")))->S.variant(v => #"DictOf123"(v)), S.dict(S.float)->S.variant(v => #"DictOfFloat"(v))])`, // (), // ) // }) -// test("Supports Object structs in union", t => { -// let struct = S.union([ +// test("Supports Object schemas in union", t => { +// let schema = S.union([ // S.object(s => s.field("field", S.literalVariant(String("123"), 123.))), // S.object(s => s.field("field", S.float)), // ]) -// let structInlineResult = S.union([ +// let schemaInlineResult = S.union([ // S.object(s => // { // "field": s.field("field", S.literal(String("123"))), @@ -660,7 +660,7 @@ test("Supports Tuple in union", t => { // )->S.variant(v => #Object2(v)), // ]) -// structInlineResult->( +// schemaInlineResult->( // U.magic: S.t< // [ // | #Object({"field": string}) @@ -670,7 +670,7 @@ test("Supports Tuple in union", t => { // ) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.object(s => // { // "field": s.field("field", S.literal(String("123"))), @@ -684,14 +684,14 @@ test("Supports Tuple in union", t => { // ) // }) -// test("Supports Tuple structs in union", t => { -// let struct = S.union([S.tuple1(. S.literalVariant(String("123"), 123.)), S.tuple1(. S.float)]) -// let structInlineResult = S.union([ +// test("Supports Tuple schemas in union", t => { +// let schema = S.union([S.tuple1(. S.literalVariant(String("123"), 123.)), S.tuple1(. S.float)]) +// let schemaInlineResult = S.union([ // S.tuple1(. S.literal(String("123")))->S.variant(v => #Tuple(v)), // S.tuple1(. S.float)->S.variant(v => #Tuple2(v)), // ]) -// structInlineResult->( +// schemaInlineResult->( // U.magic: S.t< // [ // | #Tuple(string) @@ -701,18 +701,18 @@ test("Supports Tuple in union", t => { // ) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.tuple1(. S.literal(String("123")))->S.variant(v => #"Tuple"(v)), S.tuple1(. S.float)->S.variant(v => #"Tuple2"(v))])`, // (), // ) // }) -// test("Supports Union structs in union", t => { -// let struct = S.union([ +// test("Supports Union schemas in union", t => { +// let schema = S.union([ // S.union([S.literal(String("red")), S.literal(String("blue"))]), // S.union([S.literalVariant(Int(0), "black"), S.literalVariant(Int(1), "white")]), // ]) -// let structInlineResult = S.union([ +// let schemaInlineResult = S.union([ // S.union([ // S.literalVariant(String("red"), #red), // S.literalVariant(String("blue"), #blue), @@ -722,14 +722,14 @@ test("Supports Tuple in union", t => { // ), // ]) -// structInlineResult->(U.magic: S.t<[#Union([#red | #blue]) | #Union2([#0 | #1])]> => unit) +// schemaInlineResult->(U.magic: S.t<[#Union([#red | #blue]) | #Union2([#0 | #1])]> => unit) // t->Assert.deepEqual( -// struct->S.inline, +// schema->S.inline, // `S.union([S.union([S.literalVariant(String("red"), #"red"), S.literalVariant(String("blue"), #"blue")])->S.variant(v => #"Union"(v)), S.union([S.literalVariant(Int(0), #"0"), S.literalVariant(Int(1), #"1")])->S.variant(v => #"Union2"(v))])`, // (), // ) // }) -// // TODO: Add support for recursive struct. +// // TODO: Add support for recursive schema. // // TODO: Add support for list. diff --git a/packages/tests/src/core/S_int_test.res b/packages/tests/src/core/S_int_test.res index 199fe6c3..7e940eb1 100644 --- a/packages/tests/src/core/S_int_test.res +++ b/packages/tests/src/core/S_int_test.res @@ -7,19 +7,19 @@ module Common = { let factory = () => S.int test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -29,70 +29,70 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{if(typeof i!=="number"||i>2147483647||i<-2147483648||i%1!==0){e[0](i)}return i}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) } test("Fails to parse int when JSON is a number bigger than +2^31", t => { - let struct = S.int + let schema = S.int t->Assert.deepEqual( - %raw(`2147483648`)->S.parseAnyWith(struct), + %raw(`2147483648`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`2147483648`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`2147483648`)}), operation: Parsing, path: S.Path.empty, }), ), (), ) - t->Assert.deepEqual(%raw(`2147483647`)->S.parseAnyWith(struct), Ok(2147483647), ()) + t->Assert.deepEqual(%raw(`2147483647`)->S.parseAnyWith(schema), Ok(2147483647), ()) }) test("Fails to parse int when JSON is a number lower than -2^31", t => { - let struct = S.int + let schema = S.int t->Assert.deepEqual( - %raw(`-2147483649`)->S.parseAnyWith(struct), + %raw(`-2147483649`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`-2147483649`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`-2147483649`)}), operation: Parsing, path: S.Path.empty, }), ), (), ) - t->Assert.deepEqual(%raw(`-2147483648`)->S.parseAnyWith(struct), Ok(-2147483648), ()) + t->Assert.deepEqual(%raw(`-2147483648`)->S.parseAnyWith(schema), Ok(-2147483648), ()) }) test("Fails to parse NaN", t => { - let struct = S.int + let schema = S.int t->Assert.deepEqual( - %raw(`NaN`)->S.parseAnyWith(struct), + %raw(`NaN`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`NaN`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`NaN`)}), operation: Parsing, path: S.Path.empty, }), diff --git a/packages/tests/src/core/S_isAsyncParse_test.res b/packages/tests/src/core/S_isAsyncParse_test.res index c42dffa4..b0499cf5 100644 --- a/packages/tests/src/core/S_isAsyncParse_test.res +++ b/packages/tests/src/core/S_isAsyncParse_test.res @@ -1,29 +1,29 @@ open Ava open RescriptCore -test("Returns false for struct with NoOperation", t => { +test("Returns false for schema with NoOperation", t => { t->Assert.is(S.unknown->S.isAsyncParse, false, ()) }) -test("Returns false for sync struct", t => { +test("Returns false for sync schema", t => { t->Assert.is(S.string->S.isAsyncParse, false, ()) }) -test("Returns true for async struct", t => { - let struct = S.string->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)}) +test("Returns true for async schema", t => { + let schema = S.string->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)}) - t->Assert.is(struct->S.isAsyncParse, true, ()) + t->Assert.is(schema->S.isAsyncParse, true, ()) }) -test("Returns true for async struct after running a serializer", t => { - let struct = +test("Returns true for async schema after running a serializer", t => { + let schema = S.string->S.transform(_ => {asyncParser: i => () => Promise.resolve(i), serializer: i => i}) - t->Assert.deepEqual("abc"->S.serializeWith(struct), Ok(%raw(`"abc"`)), ()) - t->Assert.is(struct->S.isAsyncParse, true, ()) + t->Assert.deepEqual("abc"->S.serializeWith(schema), Ok(%raw(`"abc"`)), ()) + t->Assert.is(schema->S.isAsyncParse, true, ()) }) -test("Returns true for struct with nested async", t => { - let struct = S.tuple1(S.string->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) +test("Returns true for schema with nested async", t => { + let schema = S.tuple1(S.string->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) - t->Assert.is(struct->S.isAsyncParse, true, ()) + t->Assert.is(schema->S.isAsyncParse, true, ()) }) diff --git a/packages/tests/src/core/S_jsonString_test.res b/packages/tests/src/core/S_jsonString_test.res index 9db8fab4..cec3af1a 100644 --- a/packages/tests/src/core/S_jsonString_test.res +++ b/packages/tests/src/core/S_jsonString_test.res @@ -2,55 +2,55 @@ open Ava open RescriptCore test("Successfully parses JSON", t => { - let struct = S.string + let schema = S.string - t->Assert.deepEqual(`"Foo"`->S.parseAnyWith(S.jsonString(struct)), Ok("Foo"), ()) + t->Assert.deepEqual(`"Foo"`->S.parseAnyWith(S.jsonString(schema)), Ok("Foo"), ()) }) test("Successfully serializes JSON", t => { - let struct = S.string + let schema = S.string t->Assert.deepEqual( - `Foo`->S.serializeToUnknownWith(S.jsonString(struct)), + `Foo`->S.serializeToUnknownWith(S.jsonString(schema)), Ok(%raw(`'"Foo"'`)), (), ) }) -test("Fails to create struct when passing non-jsonable struct to S.jsonString", t => { +test("Fails to create schema when passing non-jsonable schema to S.jsonString", t => { t->Assert.throws( () => { S.jsonString(S.object(s => s.field("foo", S.unknown))) }, ~expectations={ - message: `[rescript-struct] The struct Object({"foo": Unknown}) passed to S.jsonString is not compatible with JSON`, + message: `[rescript-schema] The schema Object({"foo": Unknown}) passed to S.jsonString is not compatible with JSON`, }, (), ) }) test("Compiled parse code snapshot", t => { - let struct = S.jsonString(S.bool) + let schema = S.jsonString(S.bool) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(typeof i!=="string"){e[2](i)}try{v0=JSON.parse(i)}catch(t){e[0](t.message)}if(typeof v0!=="boolean"){e[1](v0)}return v0}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = S.jsonString(S.bool->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) + let schema = S.jsonString(S.bool->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1;if(typeof i!=="string"){e[3](i)}try{v0=JSON.parse(i)}catch(t){e[0](t.message)}if(typeof v0!=="boolean"){e[1](v0)}v1=e[2](v0);return v1}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.jsonString(S.bool) + let schema = S.jsonString(S.bool) - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{return JSON.stringify(i)}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{return JSON.stringify(i)}`) }) diff --git a/packages/tests/src/core/S_json_test.res b/packages/tests/src/core/S_json_test.res index 06375873..34ccc13f 100644 --- a/packages/tests/src/core/S_json_test.res +++ b/packages/tests/src/core/S_json_test.res @@ -2,66 +2,66 @@ open Ava open RescriptCore test("Supports String", t => { - let struct = S.json + let schema = S.json let data = JSON.Encode.string("Foo") - t->Assert.deepEqual(data->S.parseWith(struct), Ok(data), ()) - t->Assert.deepEqual(data->S.serializeWith(struct), Ok(data), ()) + t->Assert.deepEqual(data->S.parseWith(schema), Ok(data), ()) + t->Assert.deepEqual(data->S.serializeWith(schema), Ok(data), ()) }) test("Supports Number", t => { - let struct = S.json + let schema = S.json let data = JSON.Encode.float(123.) - t->Assert.deepEqual(data->S.parseWith(struct), Ok(data), ()) - t->Assert.deepEqual(data->S.serializeWith(struct), Ok(data), ()) + t->Assert.deepEqual(data->S.parseWith(schema), Ok(data), ()) + t->Assert.deepEqual(data->S.serializeWith(schema), Ok(data), ()) }) test("Supports Bool", t => { - let struct = S.json + let schema = S.json let data = JSON.Encode.bool(true) - t->Assert.deepEqual(data->S.parseWith(struct), Ok(data), ()) - t->Assert.deepEqual(data->S.serializeWith(struct), Ok(data), ()) + t->Assert.deepEqual(data->S.parseWith(schema), Ok(data), ()) + t->Assert.deepEqual(data->S.serializeWith(schema), Ok(data), ()) }) test("Supports Null", t => { - let struct = S.json + let schema = S.json let data = JSON.Encode.null - t->Assert.deepEqual(data->S.parseWith(struct), Ok(data), ()) - t->Assert.deepEqual(data->S.serializeWith(struct), Ok(data), ()) + t->Assert.deepEqual(data->S.parseWith(schema), Ok(data), ()) + t->Assert.deepEqual(data->S.serializeWith(schema), Ok(data), ()) }) test("Supports Array", t => { - let struct = S.json + let schema = S.json let data = JSON.Encode.array([JSON.Encode.string("foo"), JSON.Encode.null]) - t->Assert.deepEqual(data->S.parseWith(struct), Ok(data), ()) - t->Assert.deepEqual(data->S.serializeWith(struct), Ok(data), ()) + t->Assert.deepEqual(data->S.parseWith(schema), Ok(data), ()) + t->Assert.deepEqual(data->S.serializeWith(schema), Ok(data), ()) }) test("Supports Object", t => { - let struct = S.json + let schema = S.json let data = JSON.Encode.object( [("bar", JSON.Encode.string("foo")), ("baz", JSON.Encode.null)]->Dict.fromArray, ) - t->Assert.deepEqual(data->S.parseWith(struct), Ok(data), ()) - t->Assert.deepEqual(data->S.serializeWith(struct), Ok(data), ()) + t->Assert.deepEqual(data->S.parseWith(schema), Ok(data), ()) + t->Assert.deepEqual(data->S.serializeWith(schema), Ok(data), ()) }) test("Fails to parse Object field", t => { - let struct = S.json + let schema = S.json let data = JSON.Encode.object( [("bar", %raw(`undefined`)), ("baz", JSON.Encode.null)]->Dict.fromArray, ) t->Assert.deepEqual( - data->S.parseWith(struct), + data->S.parseWith(schema), Error( U.error({ - code: InvalidType({received: %raw(`undefined`), expected: struct->S.toUnknown}), + code: InvalidType({received: %raw(`undefined`), expected: schema->S.toUnknown}), operation: Parsing, path: S.Path.fromLocation("bar"), }), @@ -71,14 +71,14 @@ test("Fails to parse Object field", t => { }) test("Fails to parse matrix field", t => { - let struct = S.json + let schema = S.json let data = %raw(`[1,[undefined]]`) t->Assert.deepEqual( - data->S.parseWith(struct), + data->S.parseWith(schema), Error( U.error({ - code: InvalidType({received: %raw(`undefined`), expected: struct->S.toUnknown}), + code: InvalidType({received: %raw(`undefined`), expected: schema->S.toUnknown}), operation: Parsing, path: S.Path.fromArray(["1", "0"]), }), @@ -88,12 +88,12 @@ test("Fails to parse matrix field", t => { }) test("Fails to parse NaN", t => { - let struct = S.json + let schema = S.json t->Assert.deepEqual( - %raw(`NaN`)->S.parseAnyWith(struct), + %raw(`NaN`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({received: %raw(`NaN`), expected: struct->S.toUnknown}), + code: InvalidType({received: %raw(`NaN`), expected: schema->S.toUnknown}), operation: Parsing, path: S.Path.empty, }), @@ -103,12 +103,12 @@ test("Fails to parse NaN", t => { }) test("Fails to parse undefined", t => { - let struct = S.json + let schema = S.json t->Assert.deepEqual( - %raw(`undefined`)->S.parseAnyWith(struct), + %raw(`undefined`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({received: %raw(`undefined`), expected: struct->S.toUnknown}), + code: InvalidType({received: %raw(`undefined`), expected: schema->S.toUnknown}), operation: Parsing, path: S.Path.empty, }), @@ -118,13 +118,13 @@ test("Fails to parse undefined", t => { }) test("Compiled parse code snapshot", t => { - let struct = S.json + let schema = S.json - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{return e[0](i)}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{return e[0](i)}`) }) test("Compiled serialize code snapshot", t => { - let struct = S.json + let schema = S.json - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) diff --git a/packages/tests/src/core/S_list_test.res b/packages/tests/src/core/S_list_test.res index e3f51f81..78f77b8c 100644 --- a/packages/tests/src/core/S_list_test.res +++ b/packages/tests/src/core/S_list_test.res @@ -8,15 +8,15 @@ module CommonWithNested = { let factory = () => S.list(S.string) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() - switch invalidAny->S.parseAnyWith(struct) { + switch invalidAny->S.parseAnyWith(schema) { | Ok(_) => t->Assert.fail("Unexpected result.") | Error(e) => { t->Assert.deepEqual(e.operation, Parsing, ()) @@ -24,7 +24,7 @@ module CommonWithNested = { switch e.code { | InvalidType({expected, received}) => { t->Assert.deepEqual(received, invalidAny, ()) - t->U.unsafeAssertEqualStructs(expected, struct) + t->U.unsafeAssertEqualSchemas(expected, schema) } | _ => t->Assert.fail("Unexpected code.") } @@ -33,10 +33,10 @@ module CommonWithNested = { }) test("Fails to parse nested", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - nestedInvalidAny->S.parseAnyWith(struct), + nestedInvalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: 1->Obj.magic}), @@ -49,17 +49,17 @@ module CommonWithNested = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) } test("Successfully parses list of optional items", t => { - let struct = S.list(S.option(S.string)) + let schema = S.list(S.option(S.string)) t->Assert.deepEqual( - %raw(`["a", undefined, undefined, "b"]`)->S.parseAnyWith(struct), + %raw(`["a", undefined, undefined, "b"]`)->S.parseAnyWith(schema), Ok(list{Some("a"), None, None, Some("b")}), (), ) diff --git a/packages/tests/src/core/S_literal_Array_test.res b/packages/tests/src/core/S_literal_Array_test.res index 40a86518..fa5bbf2f 100644 --- a/packages/tests/src/core/S_literal_Array_test.res +++ b/packages/tests/src/core/S_literal_Array_test.res @@ -6,16 +6,16 @@ module Common = { let factory = () => S.literal(("bar", true)) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(value->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalid->S.parseAnyWith(struct), + invalid->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -31,16 +31,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(value->U.castAnyToUnknown), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(value->U.castAnyToUnknown), ()) }) test("Fails to serialize invalid", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalid->S.serializeToUnknownWith(struct), + invalid->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -56,10 +56,10 @@ module Common = { }) test("Fails to parse array like object", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - %raw(`{0: "bar",1:true}`)->S.parseAnyWith(struct), + %raw(`{0: "bar",1:true}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -75,10 +75,10 @@ module Common = { }) test("Fails to parse array with excess item", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - %raw(`["bar", true, false]`)->S.parseAnyWith(struct), + %raw(`["bar", true, false]`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -94,20 +94,20 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{(i===e[0]||Array.isArray(i)&&i.length===2&&i[0]===e[1]&&i[1]===e[2])||e[3](i);return i}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{(i===e[0]||Array.isArray(i)&&i.length===2&&i[0]===e[1]&&i[1]===e[2])||e[3](i);return i}`, ) diff --git a/packages/tests/src/core/S_literal_Boolean_test.res b/packages/tests/src/core/S_literal_Boolean_test.res index 0311c4af..c7070eec 100644 --- a/packages/tests/src/core/S_literal_Boolean_test.res +++ b/packages/tests/src/core/S_literal_Boolean_test.res @@ -9,16 +9,16 @@ module Common = { let factory = () => S.literal(false) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Boolean(false), received: true->Obj.magic}), @@ -31,10 +31,10 @@ module Common = { }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Boolean(false), received: invalidTypeAny}), @@ -47,16 +47,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Fails to serialize invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidValue->S.serializeToUnknownWith(struct), + invalidValue->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: Boolean(false), received: invalidValue}), @@ -69,14 +69,14 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{i===e[0]||e[1](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{i===e[0]||e[1](i);return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{i===e[0]||e[1](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{i===e[0]||e[1](i);return i}`) }) } diff --git a/packages/tests/src/core/S_literal_NaN_test.res b/packages/tests/src/core/S_literal_NaN_test.res index a05e095a..a69ab59a 100644 --- a/packages/tests/src/core/S_literal_NaN_test.res +++ b/packages/tests/src/core/S_literal_NaN_test.res @@ -8,16 +8,16 @@ module Common = { let factory = () => S.literal(%raw(`NaN`)) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: NaN, received: invalidTypeAny}), @@ -30,16 +30,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Fails to serialize invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidValue->S.serializeToUnknownWith(struct), + invalidValue->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: NaN, received: invalidValue}), @@ -52,14 +52,14 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{Number.isNaN(i)||e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{Number.isNaN(i)||e[0](i);return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{Number.isNaN(i)||e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{Number.isNaN(i)||e[0](i);return i}`) }) } diff --git a/packages/tests/src/core/S_literal_Null_test.res b/packages/tests/src/core/S_literal_Null_test.res index 1d7d3b69..1dd00b83 100644 --- a/packages/tests/src/core/S_literal_Null_test.res +++ b/packages/tests/src/core/S_literal_Null_test.res @@ -9,16 +9,16 @@ module Common = { let factory = () => S.literal(Null.null) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Null, received: invalidTypeAny}), @@ -31,16 +31,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Fails to serialize invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidValue->S.serializeToUnknownWith(struct), + invalidValue->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: Null, received: invalidValue}), @@ -53,14 +53,14 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{i===null||e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{i===null||e[0](i);return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{i===null||e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{i===null||e[0](i);return i}`) }) } diff --git a/packages/tests/src/core/S_literal_Number_test.res b/packages/tests/src/core/S_literal_Number_test.res index 2c18291e..26df18fd 100644 --- a/packages/tests/src/core/S_literal_Number_test.res +++ b/packages/tests/src/core/S_literal_Number_test.res @@ -9,16 +9,16 @@ module Common = { let factory = () => S.literal(123.) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Number(123.), received: 444.->Obj.magic}), @@ -31,10 +31,10 @@ module Common = { }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Number(123.), received: invalidTypeAny}), @@ -47,16 +47,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Fails to serialize invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidValue->S.serializeToUnknownWith(struct), + invalidValue->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: Number(123.), received: invalidValue}), @@ -69,23 +69,23 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{i===e[0]||e[1](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{i===e[0]||e[1](i);return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{i===e[0]||e[1](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{i===e[0]||e[1](i);return i}`) }) } test("Formatting of negative number with a decimal point in an error message", t => { - let struct = S.literal(-123.567) + let schema = S.literal(-123.567) t->Assert.deepEqual( - %raw(`"foo"`)->S.parseAnyWith(struct), + %raw(`"foo"`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Number(-123.567), received: "foo"->Obj.magic}), diff --git a/packages/tests/src/core/S_literal_Object_test.res b/packages/tests/src/core/S_literal_Object_test.res index 14bdf37c..c54870d3 100644 --- a/packages/tests/src/core/S_literal_Object_test.res +++ b/packages/tests/src/core/S_literal_Object_test.res @@ -19,16 +19,16 @@ module Common = { external makeNotPlainValue: unit => {"foo": string} = "NotPlainValue" test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(value->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalid->S.parseAnyWith(struct), + invalid->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -44,16 +44,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(value->U.castAnyToUnknown), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(value->U.castAnyToUnknown), ()) }) test("Fails to serialize invalid", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalid->S.serializeToUnknownWith(struct), + invalid->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -69,10 +69,10 @@ module Common = { }) test("Fails to parse null", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - %raw(`null`)->S.parseAnyWith(struct), + %raw(`null`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -88,10 +88,10 @@ module Common = { }) test("Fails to parse value with excess fields", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - %raw(`{"foo": "bar","excess":true}`)->S.parseAnyWith(struct), + %raw(`{"foo": "bar","excess":true}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -107,10 +107,10 @@ module Common = { }) test("Fails to parse non plain objects", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - makeNotPlainValue()->S.parseAnyWith(struct), + makeNotPlainValue()->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -126,20 +126,20 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{(i===e[0]||i&&i.constructor===Object&&Object.keys(i).length===1&&i["foo"]===e[1])||e[2](i);return i}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{(i===e[0]||i&&i.constructor===Object&&Object.keys(i).length===1&&i["foo"]===e[1])||e[2](i);return i}`, ) diff --git a/packages/tests/src/core/S_literal_String_test.res b/packages/tests/src/core/S_literal_String_test.res index a9e7e5d7..9f0ecbf4 100644 --- a/packages/tests/src/core/S_literal_String_test.res +++ b/packages/tests/src/core/S_literal_String_test.res @@ -9,16 +9,16 @@ module Common = { let factory = () => S.literal("ReScript is Great!") test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -34,10 +34,10 @@ module Common = { }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -53,16 +53,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Fails to serialize invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidValue->S.serializeToUnknownWith(struct), + invalidValue->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({ @@ -78,14 +78,14 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{i===e[0]||e[1](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{i===e[0]||e[1](i);return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{i===e[0]||e[1](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{i===e[0]||e[1](i);return i}`) }) } diff --git a/packages/tests/src/core/S_literal_Undefined_test.res b/packages/tests/src/core/S_literal_Undefined_test.res index 7de396d2..b35ee326 100644 --- a/packages/tests/src/core/S_literal_Undefined_test.res +++ b/packages/tests/src/core/S_literal_Undefined_test.res @@ -8,16 +8,16 @@ module Common = { let factory = () => S.literal() test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Undefined, received: invalidTypeAny}), @@ -30,16 +30,16 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Fails to serialize invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidValue->S.serializeToUnknownWith(struct), + invalidValue->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: Undefined, received: invalidValue}), @@ -52,14 +52,14 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{i===void 0||e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{i===void 0||e[0](i);return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{i===void 0||e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{i===void 0||e[0](i);return i}`) }) } diff --git a/packages/tests/src/core/S_name_test.res b/packages/tests/src/core/S_name_test.res index 8afc1872..97e2fe0a 100644 --- a/packages/tests/src/core/S_name_test.res +++ b/packages/tests/src/core/S_name_test.res @@ -1,34 +1,34 @@ open Ava -test("Name of primitive struct", t => { +test("Name of primitive schema", t => { t->Assert.deepEqual(S.string->S.name, "String", ()) }) -test("Name of Literal struct", t => { +test("Name of Literal schema", t => { t->Assert.deepEqual(S.literal(123)->S.name, "Literal(123)", ()) }) -test("Name of Literal object struct", t => { +test("Name of Literal object schema", t => { t->Assert.deepEqual(S.literal({"abc": 123})->S.name, `Literal({"abc": 123})`, ()) }) -test("Name of Array struct", t => { +test("Name of Array schema", t => { t->Assert.deepEqual(S.array(S.string)->S.name, "Array(String)", ()) }) -test("Name of Dict struct", t => { +test("Name of Dict schema", t => { t->Assert.deepEqual(S.dict(S.string)->S.name, "Dict(String)", ()) }) -test("Name of Option struct", t => { +test("Name of Option schema", t => { t->Assert.deepEqual(S.option(S.string)->S.name, "Option(String)", ()) }) -test("Name of Null struct", t => { +test("Name of Null schema", t => { t->Assert.deepEqual(S.null(S.string)->S.name, "Null(String)", ()) }) -test("Name of Union struct", t => { +test("Name of Union schema", t => { t->Assert.deepEqual( S.union([S.string, S.literal("foo")])->S.name, `Union(String, Literal("foo"))`, @@ -36,7 +36,7 @@ test("Name of Union struct", t => { ) }) -test("Name of Object struct", t => { +test("Name of Object schema", t => { t->Assert.deepEqual( S.object(s => { @@ -49,7 +49,7 @@ test("Name of Object struct", t => { ) }) -test("Name of Tuple struct", t => { +test("Name of Tuple schema", t => { t->Assert.deepEqual( S.tuple(s => { @@ -62,13 +62,13 @@ test("Name of Tuple struct", t => { ) }) -test("Name of custom struct", t => { +test("Name of custom schema", t => { t->Assert.deepEqual(S.custom("Test", s => s.fail("User error"))->S.name, "Test", ()) }) -test("Name of renamed struct", t => { - let originalStruct = S.unknown - let renamedStruct = originalStruct->S.setName("Foo") - t->Assert.deepEqual(originalStruct->S.name, "Unknown", ()) - t->Assert.deepEqual(renamedStruct->S.name, "Foo", ()) +test("Name of renamed schema", t => { + let originalSchema = S.unknown + let renamedSchema = originalSchema->S.setName("Foo") + t->Assert.deepEqual(originalSchema->S.name, "Unknown", ()) + t->Assert.deepEqual(renamedSchema->S.name, "Foo", ()) }) diff --git a/packages/tests/src/core/S_never_test.res b/packages/tests/src/core/S_never_test.res index 233d8482..e3ffeb50 100644 --- a/packages/tests/src/core/S_never_test.res +++ b/packages/tests/src/core/S_never_test.res @@ -5,10 +5,10 @@ module Common = { let factory = () => S.never test("Fails to ", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - any->S.parseAnyWith(struct), + any->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.never->S.toUnknown, received: any}), @@ -21,13 +21,13 @@ module Common = { }) test("Fails to serialize ", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - any->S.serializeToUnknownWith(struct), + any->S.serializeToUnknownWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: any}), + code: InvalidType({expected: schema->S.toUnknown, received: any}), operation: Serializing, path: S.Path.empty, }), @@ -37,21 +37,21 @@ module Common = { }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{e[0](i);return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{e[0](i);return i}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{e[0](i);return i}`) }) } module ObjectField = { test("Fails to parse a object with Never field", t => { - let struct = S.object(s => + let schema = S.object(s => { "key": s.field("key", S.string), "oldKey": s.field("oldKey", S.never), @@ -59,7 +59,7 @@ module ObjectField = { ) t->Assert.deepEqual( - %raw(`{"key":"value"}`)->S.parseAnyWith(struct), + %raw(`{"key":"value"}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.never->S.toUnknown, received: %raw(`undefined`)}), @@ -72,7 +72,7 @@ module ObjectField = { }) test("Successfully parses a object with Never field when it's optional and not present", t => { - let struct = S.object(s => + let schema = S.object(s => { "key": s.field("key", S.string), "oldKey": s.field( @@ -83,7 +83,7 @@ module ObjectField = { ) t->Assert.deepEqual( - %raw(`{"key":"value"}`)->S.parseAnyWith(struct), + %raw(`{"key":"value"}`)->S.parseAnyWith(schema), Ok({ "key": "value", "oldKey": None, diff --git a/packages/tests/src/core/S_null_test.res b/packages/tests/src/core/S_null_test.res index d8f55a7c..25ba6111 100644 --- a/packages/tests/src/core/S_null_test.res +++ b/packages/tests/src/core/S_null_test.res @@ -8,19 +8,19 @@ module Common = { let factory = () => S.null(S.string) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -30,36 +30,36 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(i!==null&&(typeof i!=="string")){e[0](i)}if(i!==null){v0=i}else{v0=void 0}return v0}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = S.null(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) + let schema = S.null(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(i!==null){let v1;v1=e[0](i);v0=v1}else{v0=()=>Promise.resolve(void 0)}return v0}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;if(i!==void 0){v0=e[0](i)}else{v0=null}return v0}`, ) @@ -67,19 +67,19 @@ module Common = { } test("Successfully parses primitive", t => { - let struct = S.null(S.bool) + let schema = S.null(S.bool) - t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(struct), Ok(Some(true)), ()) + t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(schema), Ok(Some(true)), ()) }) test("Fails to parse JS undefined", t => { - let struct = S.null(S.bool) + let schema = S.null(S.bool) t->Assert.deepEqual( - %raw(`undefined`)->S.parseAnyWith(struct), + %raw(`undefined`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`undefined`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`undefined`)}), operation: Parsing, path: S.Path.empty, }), @@ -89,14 +89,14 @@ test("Fails to parse JS undefined", t => { }) test("Fails to parse object with missing field that marked as null", t => { - let fieldStruct = S.null(S.string) - let struct = S.object(s => s.field("nullableField", fieldStruct)) + let fieldSchema = S.null(S.string) + let schema = S.object(s => s.field("nullableField", fieldSchema)) t->Assert.deepEqual( - %raw(`{}`)->S.parseAnyWith(struct), + %raw(`{}`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: fieldStruct->S.toUnknown, received: %raw(`undefined`)}), + code: InvalidType({expected: fieldSchema->S.toUnknown, received: %raw(`undefined`)}), operation: Parsing, path: S.Path.fromArray(["nullableField"]), }), @@ -105,14 +105,14 @@ test("Fails to parse object with missing field that marked as null", t => { ) }) -test("Fails to parse JS null when struct doesn't allow optional data", t => { - let struct = S.bool +test("Fails to parse JS null when schema doesn't allow optional data", t => { + let schema = S.bool t->Assert.deepEqual( - %raw(`null`)->S.parseAnyWith(struct), + %raw(`null`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`null`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`null`)}), operation: Parsing, path: S.Path.empty, }), @@ -121,26 +121,26 @@ test("Fails to parse JS null when struct doesn't allow optional data", t => { ) }) -test("Successfully parses null and serializes it back for deprecated nullable struct", t => { - let struct = S.null(S.bool)->S.deprecate("Deprecated") +test("Successfully parses null and serializes it back for deprecated nullable schema", t => { + let schema = S.null(S.bool)->S.deprecate("Deprecated") t->Assert.deepEqual( - %raw(`null`)->S.parseAnyWith(struct)->Result.map(S.serializeToUnknownWith(_, struct)), + %raw(`null`)->S.parseAnyWith(schema)->Result.map(S.serializeToUnknownWith(_, schema)), Ok(Ok(%raw(`null`))), (), ) }) test("Parses null nested in option as None instead of Some(None)", t => { - let struct = S.option(S.null(S.bool)) + let schema = S.option(S.null(S.bool)) - t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(struct), Ok(None), ()) - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok(None), ()) + t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(schema), Ok(None), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok(None), ()) }) test("Serializes Some(None) to null for null nested in option", t => { - let struct = S.option(S.null(S.bool)) + let schema = S.option(S.null(S.bool)) - t->Assert.deepEqual(Some(None)->S.serializeToUnknownWith(struct), Ok(%raw(`null`)), ()) - t->Assert.deepEqual(None->S.serializeToUnknownWith(struct), Ok(%raw(`undefined`)), ()) + t->Assert.deepEqual(Some(None)->S.serializeToUnknownWith(schema), Ok(%raw(`null`)), ()) + t->Assert.deepEqual(None->S.serializeToUnknownWith(schema), Ok(%raw(`undefined`)), ()) }) diff --git a/packages/tests/src/core/S_object_discriminant_test.res b/packages/tests/src/core/S_object_discriminant_test.res index 550e3850..84a854d9 100644 --- a/packages/tests/src/core/S_object_discriminant_test.res +++ b/packages/tests/src/core/S_object_discriminant_test.res @@ -4,18 +4,18 @@ open RescriptCore module Positive = { module TestData = { type t = { - discriminantStruct: S.t, + discriminantSchema: S.t, discriminantData: unknown, testNamePostfix: string, } let make = ( - ~discriminantStruct: S.t<'value>, + ~discriminantSchema: S.t<'value>, ~discriminantData: 'any, ~description as maybeDescription=?, (), ) => { - discriminantStruct: discriminantStruct->Obj.magic, + discriminantSchema: discriminantSchema->Obj.magic, discriminantData: discriminantData->Obj.magic, testNamePostfix: switch maybeDescription { | Some(description) => ` ${description}` @@ -26,71 +26,71 @@ module Positive = { [ TestData.make( - ~discriminantStruct=S.literal("asdf"), + ~discriminantSchema=S.literal("asdf"), ~discriminantData=%raw(`"asdf"`), ~description="String", (), ), TestData.make( - ~discriminantStruct=S.literal("\"\'\`"), + ~discriminantSchema=S.literal("\"\'\`"), ~discriminantData=%raw(`"\"\'\`"`), ~description="String which needs to be escaped", (), ), TestData.make( - ~discriminantStruct=S.literal(123), + ~discriminantSchema=S.literal(123), ~discriminantData=%raw("123"), ~description="Int", (), ), TestData.make( - ~discriminantStruct=S.literal(1.3), + ~discriminantSchema=S.literal(1.3), ~discriminantData=%raw("1.3"), ~description="Float", (), ), TestData.make( - ~discriminantStruct=S.literal(true), + ~discriminantSchema=S.literal(true), ~discriminantData=%raw("true"), ~description="Bool", (), ), TestData.make( - ~discriminantStruct=S.literal(), + ~discriminantSchema=S.literal(), ~discriminantData=%raw(`undefined`), ~description="Unit", (), ), TestData.make( - ~discriminantStruct=S.literal(Null.null), + ~discriminantSchema=S.literal(Null.null), ~discriminantData=%raw(`null`), ~description="Null", (), ), TestData.make( - ~discriminantStruct=S.literal(%raw(`NaN`)), + ~discriminantSchema=S.literal(%raw(`NaN`)), ~discriminantData=%raw(`NaN`), ~description="NaN", (), ), TestData.make( - ~discriminantStruct=S.union([S.literal(false), S.bool]), + ~discriminantSchema=S.union([S.literal(false), S.bool]), ~discriminantData=%raw("false"), (), ), TestData.make( - ~discriminantStruct=S.tuple2(S.literal(false), S.literal("bar")), + ~discriminantSchema=S.tuple2(S.literal(false), S.literal("bar")), ~discriminantData=%raw(`[false, "bar"]`), (), ), TestData.make( - ~discriminantStruct=S.literal((false, "bar")), + ~discriminantSchema=S.literal((false, "bar")), ~discriminantData=%raw(`[false, "bar"]`), ~description="Tuple", (), ), TestData.make( - ~discriminantStruct=S.object(s => { + ~discriminantSchema=S.object(s => { ignore(s.field("nestedDiscriminant", S.literal("abc"))) { "field": s.field("nestedField", S.literal(false)), @@ -104,7 +104,7 @@ module Positive = { ), TestData.make( ~description="and values needed to be escaped", - ~discriminantStruct=S.object(s => { + ~discriminantSchema=S.object(s => { ignore(s.field("\"\'\`", S.literal("\"\'\`"))) { "field": s.field("nestedField", S.literal(false)), @@ -118,11 +118,11 @@ module Positive = { ), ]->Array.forEach(testData => { test( - `Successfully parses object with discriminant "${testData.discriminantStruct->S.name}"${testData.testNamePostfix}`, + `Successfully parses object with discriminant "${testData.discriminantSchema->S.name}"${testData.testNamePostfix}`, t => { - let struct = S.object( + let schema = S.object( s => { - ignore(s.field("discriminant", testData.discriminantStruct)) + ignore(s.field("discriminant", testData.discriminantSchema)) { "field": s.field("field", S.string), } @@ -133,7 +133,7 @@ module Positive = { { "discriminant": testData.discriminantData, "field": "bar", - }->S.parseAnyWith(struct), + }->S.parseAnyWith(schema), Ok({"field": "bar"}), (), ) @@ -141,11 +141,11 @@ module Positive = { ) test( - `Successfully serializes object with discriminant "${testData.discriminantStruct->S.name}"${testData.testNamePostfix}`, + `Successfully serializes object with discriminant "${testData.discriminantSchema->S.name}"${testData.testNamePostfix}`, t => { - let struct = S.object( + let schema = S.object( s => { - ignore(s.field("discriminant", testData.discriminantStruct)) + ignore(s.field("discriminant", testData.discriminantSchema)) { "field": s.field("field", S.string), } @@ -153,7 +153,7 @@ module Positive = { ) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Ok( { "discriminant": testData.discriminantData, @@ -170,18 +170,18 @@ module Positive = { module Negative = { module TestData = { type t = { - discriminantStruct: S.t, + discriminantSchema: S.t, discriminantData: unknown, testNamePostfix: string, } let make = ( - ~discriminantStruct: S.t<'value>, + ~discriminantSchema: S.t<'value>, ~discriminantData: 'any, ~description as maybeDescription=?, (), ) => { - discriminantStruct: discriminantStruct->Obj.magic, + discriminantSchema: discriminantSchema->Obj.magic, discriminantData: discriminantData->Obj.magic, testNamePostfix: switch maybeDescription { | Some(description) => ` ${description}` @@ -191,41 +191,41 @@ module Negative = { } [ - TestData.make(~discriminantStruct=S.string, ~discriminantData="foo", ()), - TestData.make(~discriminantStruct=S.int, ~discriminantData=123, ()), - TestData.make(~discriminantStruct=S.float, ~discriminantData=123., ()), - TestData.make(~discriminantStruct=S.bool, ~discriminantData=true, ()), - TestData.make(~discriminantStruct=S.option(S.literal(true)), ~discriminantData=None, ()), - TestData.make(~discriminantStruct=S.null(S.literal(true)), ~discriminantData=%raw(`null`), ()), - TestData.make(~discriminantStruct=S.unknown, ~discriminantData="anything", ()), - TestData.make(~discriminantStruct=S.array(S.literal(true)), ~discriminantData=[true, true], ()), + TestData.make(~discriminantSchema=S.string, ~discriminantData="foo", ()), + TestData.make(~discriminantSchema=S.int, ~discriminantData=123, ()), + TestData.make(~discriminantSchema=S.float, ~discriminantData=123., ()), + TestData.make(~discriminantSchema=S.bool, ~discriminantData=true, ()), + TestData.make(~discriminantSchema=S.option(S.literal(true)), ~discriminantData=None, ()), + TestData.make(~discriminantSchema=S.null(S.literal(true)), ~discriminantData=%raw(`null`), ()), + TestData.make(~discriminantSchema=S.unknown, ~discriminantData="anything", ()), + TestData.make(~discriminantSchema=S.array(S.literal(true)), ~discriminantData=[true, true], ()), TestData.make( - ~discriminantStruct=S.dict(S.literal(true)), + ~discriminantSchema=S.dict(S.literal(true)), ~discriminantData=Dict.fromArray([("foo", true), ("bar", true)]), (), ), TestData.make( - ~discriminantStruct=S.tuple2(S.literal(true), S.bool), + ~discriminantSchema=S.tuple2(S.literal(true), S.bool), ~discriminantData=(true, false), (), ), TestData.make( - ~discriminantStruct=S.object(s => s.field("field", S.bool)), + ~discriminantSchema=S.object(s => s.field("field", S.bool)), ~discriminantData={"field": true}, (), ), TestData.make( - ~discriminantStruct=S.union([S.bool, S.literal(false)]), + ~discriminantSchema=S.union([S.bool, S.literal(false)]), ~discriminantData=true, (), ), ]->Array.forEach(testData => { test( - `Successfully parses object with discriminant that we don't know how to serialize "${testData.discriminantStruct->S.name}"${testData.testNamePostfix}`, + `Successfully parses object with discriminant that we don't know how to serialize "${testData.discriminantSchema->S.name}"${testData.testNamePostfix}`, t => { - let struct = S.object( + let schema = S.object( s => { - ignore(s.field("discriminant", testData.discriminantStruct)) + ignore(s.field("discriminant", testData.discriminantSchema)) { "field": s.field("field", S.string), } @@ -236,7 +236,7 @@ module Negative = { { "discriminant": testData.discriminantData, "field": "bar", - }->S.parseAnyWith(struct), + }->S.parseAnyWith(schema), Ok({"field": "bar"}), (), ) @@ -244,11 +244,11 @@ module Negative = { ) test( - `Fails to serialize object with discriminant that we don't know how to serialize "${testData.discriminantStruct->S.name}"${testData.testNamePostfix}`, + `Fails to serialize object with discriminant that we don't know how to serialize "${testData.discriminantSchema->S.name}"${testData.testNamePostfix}`, t => { - let struct = S.object( + let schema = S.object( s => { - ignore(s.field("discriminant", testData.discriminantStruct)) + ignore(s.field("discriminant", testData.discriminantSchema)) { "field": s.field("field", S.string), } @@ -256,7 +256,7 @@ module Negative = { ) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({ @@ -274,7 +274,7 @@ module Negative = { } test(`Fails to parse object with invalid data passed to discriminant field`, t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("discriminant", S.string)) { "field": s.field("field", S.string), @@ -285,7 +285,7 @@ test(`Fails to parse object with invalid data passed to discriminant field`, t = { "discriminant": false, "field": "bar", - }->S.parseAnyWith(struct), + }->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: Obj.magic(false)}), @@ -298,7 +298,7 @@ test(`Fails to parse object with invalid data passed to discriminant field`, t = }) test(`Parses discriminant fields before registered fields`, t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("discriminant", S.string)) { "field": s.field("field", S.string), @@ -309,7 +309,7 @@ test(`Parses discriminant fields before registered fields`, t => { { "discriminant": false, "field": false, - }->S.parseAnyWith(struct), + }->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: Obj.magic(false)}), @@ -322,7 +322,7 @@ test(`Parses discriminant fields before registered fields`, t => { }) test(`Fails to serialize object with discriminant "Never"`, t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("discriminant", S.never)) { "field": s.field("field", S.string), @@ -330,7 +330,7 @@ test(`Fails to serialize object with discriminant "Never"`, t => { }) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({ @@ -345,7 +345,7 @@ test(`Fails to serialize object with discriminant "Never"`, t => { }) test(`Serializes constant fields before registered fields`, t => { - let struct = S.object(s => { + let schema = S.object(s => { { "field": s.field("field", S.literal(true)), "constant": true, @@ -353,7 +353,7 @@ test(`Serializes constant fields before registered fields`, t => { }) t->Assert.deepEqual( - {"constant": false, "field": false}->S.serializeToUnknownWith(struct), + {"constant": false, "field": false}->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: Boolean(true), received: Obj.magic(false)}), diff --git a/packages/tests/src/core/S_object_escaping_test.res b/packages/tests/src/core/S_object_escaping_test.res index 4a4ae8ea..d56b3f10 100644 --- a/packages/tests/src/core/S_object_escaping_test.res +++ b/packages/tests/src/core/S_object_escaping_test.res @@ -2,55 +2,55 @@ open Ava open RescriptCore test("Successfully parses object with quotes in a field name", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("\"\'\`", S.string), } ) - t->Assert.deepEqual(%raw(`{"\"\'\`": "bar"}`)->S.parseAnyWith(struct), Ok({"field": "bar"}), ()) + t->Assert.deepEqual(%raw(`{"\"\'\`": "bar"}`)->S.parseAnyWith(schema), Ok({"field": "bar"}), ()) }) test("Successfully serializing object with quotes in a field name", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("\"\'\`", S.string), } ) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Ok(%raw(`{"\"\'\`": "bar"}`)), (), ) }) test("Successfully parses object transformed to object with quotes in a field name", t => { - let struct = S.object(s => + let schema = S.object(s => { "\"\'\`": s.field("field", S.string), } ) - t->Assert.deepEqual(%raw(`{"field": "bar"}`)->S.parseAnyWith(struct), Ok({"\"\'\`": "bar"}), ()) + t->Assert.deepEqual(%raw(`{"field": "bar"}`)->S.parseAnyWith(schema), Ok({"\"\'\`": "bar"}), ()) }) test("Successfully serializes object transformed to object with quotes in a field name", t => { - let struct = S.object(s => + let schema = S.object(s => { "\"\'\`": s.field("field", S.string), } ) t->Assert.deepEqual( - {"\"\'\`": "bar"}->S.serializeToUnknownWith(struct), + {"\"\'\`": "bar"}->S.serializeToUnknownWith(schema), Ok(%raw(`{"field": "bar"}`)), (), ) }) test("Successfully parses object with discriminant which has quotes as the field name", t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("\"\'\`", S.literal(Null.null))) { "field": s.field("field", S.string), @@ -61,14 +61,14 @@ test("Successfully parses object with discriminant which has quotes as the field %raw(`{ "\"\'\`": null, "field": "bar", - }`)->S.parseAnyWith(struct), + }`)->S.parseAnyWith(schema), Ok({"field": "bar"}), (), ) }) test("Successfully serializes object with discriminant which has quotes as the field name", t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("\"\'\`", S.literal(Null.null))) { "field": s.field("field", S.string), @@ -76,7 +76,7 @@ test("Successfully serializes object with discriminant which has quotes as the f }) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Ok( %raw(`{ "\"\'\`": null, @@ -88,7 +88,7 @@ test("Successfully serializes object with discriminant which has quotes as the f }) test("Successfully parses object with discriminant which has quotes as the literal value", t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("kind", S.literal("\"\'\`"))) { "field": s.field("field", S.string), @@ -99,7 +99,7 @@ test("Successfully parses object with discriminant which has quotes as the liter %raw(`{ "kind": "\"\'\`", "field": "bar", - }`)->S.parseAnyWith(struct), + }`)->S.parseAnyWith(schema), Ok({"field": "bar"}), (), ) @@ -108,7 +108,7 @@ test("Successfully parses object with discriminant which has quotes as the liter test( "Successfully serializes object with discriminant which has quotes as the literal value", t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("kind", S.literal("\"\'\`"))) { "field": s.field("field", S.string), @@ -116,7 +116,7 @@ test( }) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Ok( %raw(`{ "kind": "\"\'\`", @@ -131,7 +131,7 @@ test( test( "Successfully parses object transformed to object with quotes in name of hardcoded field", t => { - let struct = S.object(s => + let schema = S.object(s => { "\"\'\`": "hardcoded", "field": s.field("field", S.string), @@ -139,7 +139,7 @@ test( ) t->Assert.deepEqual( - %raw(`{"field": "bar"}`)->S.parseAnyWith(struct), + %raw(`{"field": "bar"}`)->S.parseAnyWith(schema), Ok({ "\"\'\`": "hardcoded", "field": "bar", @@ -152,7 +152,7 @@ test( test( "Successfully serializes object transformed to object with quotes in name of hardcoded field", t => { - let struct = S.object(s => + let schema = S.object(s => { "\"\'\`": "hardcoded", "field": s.field("field", S.string), @@ -163,7 +163,7 @@ test( { "\"\'\`": "hardcoded", "field": "bar", - }->S.serializeToUnknownWith(struct), + }->S.serializeToUnknownWith(schema), Ok(%raw(`{"field": "bar"}`)), (), ) @@ -173,7 +173,7 @@ test( test( "Successfully parses object transformed to object with quotes in value of hardcoded field", t => { - let struct = S.object(s => + let schema = S.object(s => { "hardcoded": "\"\'\`", "field": s.field("field", S.string), @@ -181,7 +181,7 @@ test( ) t->Assert.deepEqual( - %raw(`{"field": "bar"}`)->S.parseAnyWith(struct), + %raw(`{"field": "bar"}`)->S.parseAnyWith(schema), Ok({ "hardcoded": "\"\'\`", "field": "bar", @@ -194,7 +194,7 @@ test( test( "Successfully serializes object transformed to object with quotes in value of hardcoded field", t => { - let struct = S.object(s => + let schema = S.object(s => { "hardcoded": "\"\'\`", "field": s.field("field", S.string), @@ -205,7 +205,7 @@ test( { "hardcoded": "\"\'\`", "field": "bar", - }->S.serializeToUnknownWith(struct), + }->S.serializeToUnknownWith(schema), Ok(%raw(`{"field": "bar"}`)), (), ) @@ -213,14 +213,14 @@ test( ) test("Has proper error path when fails to parse object with quotes in a field name", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("\"\'\`", S.string->S.refine(s => _ => s.fail("User error"))), } ) t->Assert.deepEqual( - %raw(`{"\"\'\`": "bar"}`)->S.parseAnyWith(struct), + %raw(`{"\"\'\`": "bar"}`)->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -233,14 +233,14 @@ test("Has proper error path when fails to parse object with quotes in a field na }) test("Has proper error path when fails to serialize object with quotes in a field name", t => { - let struct = S.object(s => + let schema = S.object(s => Dict.fromArray([ ("\"\'\`", s.field("field", S.string->S.refine(s => _ => s.fail("User error")))), ]) ) t->Assert.deepEqual( - Dict.fromArray([("\"\'\`", "bar")])->S.serializeToUnknownWith(struct), + Dict.fromArray([("\"\'\`", "bar")])->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -253,14 +253,14 @@ test("Has proper error path when fails to serialize object with quotes in a fiel }) test("Field name in a format of a path is handled properly", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field(`["abc"]["cde"]`, S.string), } ) t->Assert.deepEqual( - %raw(`{"bar": "foo"}`)->S.parseAnyWith(struct), + %raw(`{"bar": "foo"}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: %raw(`undefined`)}), diff --git a/packages/tests/src/core/S_object_spread_test.res b/packages/tests/src/core/S_object_spread_test.res index c85fcb4e..6b92ab1d 100644 --- a/packages/tests/src/core/S_object_spread_test.res +++ b/packages/tests/src/core/S_object_spread_test.res @@ -13,8 +13,8 @@ type z = { ...y, } -test("Successfully parses manually created struct using type spread", t => { - let zStruct = S.object(s => { +test("Successfully parses manually created schema using type spread", t => { + let zSchema = S.object(s => { a: s.field("a", S.int), b: s.field("b", S.int), c: s.field("c", S.float), @@ -22,7 +22,7 @@ test("Successfully parses manually created struct using type spread", t => { }) t->Assert.deepEqual( - %raw(`{a: 1, b: 2, c: 3.3, d: true}`)->S.parseAnyWith(zStruct), + %raw(`{a: 1, b: 2, c: 3.3, d: true}`)->S.parseAnyWith(zSchema), Ok({a: 1, b: 2, c: 3.3, d: true}), (), ) diff --git a/packages/tests/src/core/S_object_test.res b/packages/tests/src/core/S_object_test.res index 5ae362d9..b5b194a8 100644 --- a/packages/tests/src/core/S_object_test.res +++ b/packages/tests/src/core/S_object_test.res @@ -5,24 +5,24 @@ open RescriptCore type options = {fast?: bool, mode?: int} test("Successfully parses object with inlinable string field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.string), } ) - t->Assert.deepEqual(%raw(`{field: "bar"}`)->S.parseAnyWith(struct), Ok({"field": "bar"}), ()) + t->Assert.deepEqual(%raw(`{field: "bar"}`)->S.parseAnyWith(schema), Ok({"field": "bar"}), ()) }) test("Fails to parse object with inlinable string field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.string), } ) t->Assert.deepEqual( - %raw(`{field: 123}`)->S.parseAnyWith(struct), + %raw(`{field: 123}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.string->S.toUnknown, received: %raw(`123`)}), @@ -37,14 +37,14 @@ test("Fails to parse object with inlinable string field", t => { test( "Fails to parse object with custom user error in array field (should have correct path)", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.array(S.string->S.refine(s => _ => s.fail("User error")))), } ) t->Assert.deepEqual( - %raw(`{field: ["foo"]}`)->S.parseAnyWith(struct), + %raw(`{field: ["foo"]}`)->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -58,24 +58,24 @@ test( ) test("Successfully parses object with inlinable bool field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.bool), } ) - t->Assert.deepEqual(%raw(`{field: true}`)->S.parseAnyWith(struct), Ok({"field": true}), ()) + t->Assert.deepEqual(%raw(`{field: true}`)->S.parseAnyWith(schema), Ok({"field": true}), ()) }) test("Fails to parse object with inlinable bool field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.bool), } ) t->Assert.deepEqual( - %raw(`{field: 123}`)->S.parseAnyWith(struct), + %raw(`{field: 123}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.bool->S.toUnknown, received: %raw(`123`)}), @@ -88,42 +88,42 @@ test("Fails to parse object with inlinable bool field", t => { }) test("Successfully parses object with unknown field (Noop operation)", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.unknown), } ) t->Assert.deepEqual( - %raw(`{field: new Date("2015-12-12")}`)->S.parseAnyWith(struct), + %raw(`{field: new Date("2015-12-12")}`)->S.parseAnyWith(schema), Ok(%raw(`{field: new Date("2015-12-12")}`)), (), ) }) test("Successfully serializes object with unknown field (Noop operation)", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.unknown), } ) t->Assert.deepEqual( - %raw(`{field: new Date("2015-12-12")}`)->S.serializeToUnknownWith(struct), + %raw(`{field: new Date("2015-12-12")}`)->S.serializeToUnknownWith(schema), Ok(%raw(`{field: new Date("2015-12-12")}`)), (), ) }) test("Fails to parse object with inlinable never field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.never), } ) t->Assert.deepEqual( - %raw(`{field: true}`)->S.parseAnyWith(struct), + %raw(`{field: true}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.never->S.toUnknown, received: %raw(`true`)}), @@ -136,24 +136,24 @@ test("Fails to parse object with inlinable never field", t => { }) test("Successfully parses object with inlinable float field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.float), } ) - t->Assert.deepEqual(%raw(`{field: 123}`)->S.parseAnyWith(struct), Ok({"field": 123.}), ()) + t->Assert.deepEqual(%raw(`{field: 123}`)->S.parseAnyWith(schema), Ok({"field": 123.}), ()) }) test("Fails to parse object with inlinable float field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.float), } ) t->Assert.deepEqual( - %raw(`{field: true}`)->S.parseAnyWith(struct), + %raw(`{field: true}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.float->S.toUnknown, received: %raw(`true`)}), @@ -166,24 +166,24 @@ test("Fails to parse object with inlinable float field", t => { }) test("Successfully parses object with inlinable int field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.int), } ) - t->Assert.deepEqual(%raw(`{field: 123}`)->S.parseAnyWith(struct), Ok({"field": 123}), ()) + t->Assert.deepEqual(%raw(`{field: 123}`)->S.parseAnyWith(schema), Ok({"field": 123}), ()) }) test("Fails to parse object with inlinable int field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.int), } ) t->Assert.deepEqual( - %raw(`{field: true}`)->S.parseAnyWith(struct), + %raw(`{field: true}`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidType({expected: S.int->S.toUnknown, received: %raw(`true`)}), @@ -196,28 +196,28 @@ test("Fails to parse object with inlinable int field", t => { }) test("Successfully parses object with not inlinable empty object field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.object(_ => ())), } ) - t->Assert.deepEqual(%raw(`{field: {}}`)->S.parseAnyWith(struct), Ok({"field": ()}), ()) + t->Assert.deepEqual(%raw(`{field: {}}`)->S.parseAnyWith(schema), Ok({"field": ()}), ()) }) test("Fails to parse object with not inlinable empty object field", t => { - let fieldStruct = S.object(_ => ()) - let struct = S.object(s => + let fieldSchema = S.object(_ => ()) + let schema = S.object(s => { - "field": s.field("field", fieldStruct), + "field": s.field("field", fieldSchema), } ) t->Assert.deepEqual( - %raw(`{field: true}`)->S.parseAnyWith(struct), + %raw(`{field: true}`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: fieldStruct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: fieldSchema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.fromArray(["field"]), }), @@ -227,17 +227,17 @@ test("Fails to parse object with not inlinable empty object field", t => { }) test("Fails to parse object when provided invalid data", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.string), } ) t->Assert.deepEqual( - %raw(`12`)->S.parseAnyWith(struct), + %raw(`12`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`12`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`12`)}), operation: Parsing, path: S.Path.empty, }), @@ -247,21 +247,21 @@ test("Fails to parse object when provided invalid data", t => { }) test("Successfully serializes object with single field", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.string), } ) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Ok(%raw(`{field: "bar"}`)), (), ) }) test("Successfully parses object with multiple fields", t => { - let struct = S.object(s => + let schema = S.object(s => { "boo": s.field("boo", S.string), "zoo": s.field("zoo", S.string), @@ -269,14 +269,14 @@ test("Successfully parses object with multiple fields", t => { ) t->Assert.deepEqual( - %raw(`{boo: "bar", zoo: "jee"}`)->S.parseAnyWith(struct), + %raw(`{boo: "bar", zoo: "jee"}`)->S.parseAnyWith(schema), Ok({"boo": "bar", "zoo": "jee"}), (), ) }) test("Successfully serializes object with multiple fields", t => { - let struct = S.object(s => + let schema = S.object(s => { "boo": s.field("boo", S.string), "zoo": s.field("zoo", S.string), @@ -284,14 +284,14 @@ test("Successfully serializes object with multiple fields", t => { ) t->Assert.deepEqual( - {"boo": "bar", "zoo": "jee"}->S.serializeToUnknownWith(struct), + {"boo": "bar", "zoo": "jee"}->S.serializeToUnknownWith(schema), Ok(%raw(`{boo: "bar", zoo: "jee"}`)), (), ) }) test("Successfully parses object with transformed field", t => { - let struct = S.object(s => + let schema = S.object(s => { "string": s.field( "string", @@ -301,21 +301,21 @@ test("Successfully parses object with transformed field", t => { ) t->Assert.deepEqual( - %raw(`{string: "bar"}`)->S.parseAnyWith(struct), + %raw(`{string: "bar"}`)->S.parseAnyWith(schema), Ok({"string": "barfield"}), (), ) }) test("Fails to parse object when transformed field has raises error", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field("field", S.string->S.transform(s => {parser: _ => s.fail("User error")})), } ) t->Assert.deepEqual( - {"field": "bar"}->S.parseAnyWith(struct), + {"field": "bar"}->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -328,7 +328,7 @@ test("Fails to parse object when transformed field has raises error", t => { }) test("Shows transformed object field name in error path when fails to parse", t => { - let struct = S.object(s => + let schema = S.object(s => { "transformedFieldName": s.field( "originalFieldName", @@ -338,7 +338,7 @@ test("Shows transformed object field name in error path when fails to parse", t ) t->Assert.deepEqual( - {"originalFieldName": "bar"}->S.parseAnyWith(struct), + {"originalFieldName": "bar"}->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -351,7 +351,7 @@ test("Shows transformed object field name in error path when fails to parse", t }) test("Successfully serializes object with transformed field", t => { - let struct = S.object(s => + let schema = S.object(s => { "string": s.field( "string", @@ -361,14 +361,14 @@ test("Successfully serializes object with transformed field", t => { ) t->Assert.deepEqual( - {"string": "bar"}->S.serializeToUnknownWith(struct), + {"string": "bar"}->S.serializeToUnknownWith(schema), Ok(%raw(`{"string": "barfield"}`)), (), ) }) test("Fails to serializes object when transformed field has raises error", t => { - let struct = S.object(s => + let schema = S.object(s => { "field": s.field( "field", @@ -378,7 +378,7 @@ test("Fails to serializes object when transformed field has raises error", t => ) t->Assert.deepEqual( - {"field": "bar"}->S.serializeToUnknownWith(struct), + {"field": "bar"}->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -391,7 +391,7 @@ test("Fails to serializes object when transformed field has raises error", t => }) test("Shows transformed object field name in error path when fails to serializes", t => { - let struct = S.object(s => + let schema = S.object(s => { "transformedFieldName": s.field( "originalFieldName", @@ -401,7 +401,7 @@ test("Shows transformed object field name in error path when fails to serializes ) t->Assert.deepEqual( - {"transformedFieldName": "bar"}->S.serializeToUnknownWith(struct), + {"transformedFieldName": "bar"}->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -414,7 +414,7 @@ test("Shows transformed object field name in error path when fails to serializes }) test("Shows transformed to nested object field name in error path when fails to serializes", t => { - let struct = S.object(s => + let schema = S.object(s => { "v1": { "transformedFieldName": s.field( @@ -430,7 +430,7 @@ test("Shows transformed to nested object field name in error path when fails to "v1": { "transformedFieldName": "bar", }, - }->S.serializeToUnknownWith(struct), + }->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -443,7 +443,7 @@ test("Shows transformed to nested object field name in error path when fails to }) test("Successfully parses object with optional fields", t => { - let struct = S.object(s => + let schema = S.object(s => { "boo": s.field("boo", S.option(S.string)), "zoo": s.field("zoo", S.option(S.string)), @@ -451,14 +451,14 @@ test("Successfully parses object with optional fields", t => { ) t->Assert.deepEqual( - %raw(`{boo: "bar"}`)->S.parseAnyWith(struct), + %raw(`{boo: "bar"}`)->S.parseAnyWith(schema), Ok({"boo": Some("bar"), "zoo": None}), (), ) }) test("Successfully serializes object with optional fields", t => { - let struct = S.object(s => + let schema = S.object(s => { "boo": s.field("boo", S.option(S.string)), "zoo": s.field("zoo", S.option(S.string)), @@ -466,14 +466,14 @@ test("Successfully serializes object with optional fields", t => { ) t->Assert.deepEqual( - {"boo": Some("bar"), "zoo": None}->S.serializeToUnknownWith(struct), + {"boo": Some("bar"), "zoo": None}->S.serializeToUnknownWith(schema), Ok(%raw(`{boo: "bar", zoo: undefined}`)), (), ) }) test("Successfully parses object with optional fields with default", t => { - let struct = S.object(s => + let schema = S.object(s => { "boo": s.fieldOr("boo", S.string, "default boo"), "zoo": s.fieldOr("zoo", S.string, "default zoo"), @@ -481,14 +481,14 @@ test("Successfully parses object with optional fields with default", t => { ) t->Assert.deepEqual( - %raw(`{boo: "bar"}`)->S.parseAnyWith(struct), + %raw(`{boo: "bar"}`)->S.parseAnyWith(schema), Ok({"boo": "bar", "zoo": "default zoo"}), (), ) }) test("Successfully serializes object with optional fields with default", t => { - let struct = S.object(s => + let schema = S.object(s => { "boo": s.fieldOr("boo", S.string, "default boo"), "zoo": s.fieldOr("zoo", S.string, "default zoo"), @@ -496,7 +496,7 @@ test("Successfully serializes object with optional fields with default", t => { ) t->Assert.deepEqual( - {"boo": "bar", "zoo": "baz"}->S.serializeToUnknownWith(struct), + {"boo": "bar", "zoo": "baz"}->S.serializeToUnknownWith(schema), Ok(%raw(`{boo: "bar", zoo: "baz"}`)), (), ) @@ -505,7 +505,7 @@ test("Successfully serializes object with optional fields with default", t => { test( "Successfully parses object with optional fields using (?). The optinal field becomes undefined instead of beeing missing", t => { - let optionsStruct = S.object(s => { + let optionsSchema = S.object(s => { { fast: ?s.field("fast", S.option(S.bool)), mode: s.field("mode", S.int), @@ -513,7 +513,7 @@ test( }) t->Assert.deepEqual( - %raw(`{mode: 1}`)->S.parseAnyWith(optionsStruct), + %raw(`{mode: 1}`)->S.parseAnyWith(optionsSchema), Ok({ fast: %raw(`undefined`), mode: 1, @@ -524,7 +524,7 @@ test( ) test("Successfully serializes object with optional fields using (?)", t => { - let optionsStruct = S.object(s => { + let optionsSchema = S.object(s => { { fast: ?s.field("fast", S.option(S.bool)), mode: s.field("mode", S.int), @@ -532,14 +532,14 @@ test("Successfully serializes object with optional fields using (?)", t => { }) t->Assert.deepEqual( - {mode: 1}->S.serializeToUnknownWith(optionsStruct), + {mode: 1}->S.serializeToUnknownWith(optionsSchema), Ok(%raw(`{mode: 1, fast: undefined}`)), (), ) }) test("Successfully parses object with mapped field names", t => { - let struct = S.object(s => + let schema = S.object(s => { "name": s.field("Name", S.string), "email": s.field("Email", S.string), @@ -548,14 +548,14 @@ test("Successfully parses object with mapped field names", t => { ) t->Assert.deepEqual( - %raw(`{"Name":"Dmitry","Email":"dzakh.dev@gmail.com","Age":21}`)->S.parseAnyWith(struct), + %raw(`{"Name":"Dmitry","Email":"dzakh.dev@gmail.com","Age":21}`)->S.parseAnyWith(schema), Ok({"name": "Dmitry", "email": "dzakh.dev@gmail.com", "age": 21}), (), ) }) test("Successfully serializes object with mapped field", t => { - let struct = S.object(s => + let schema = S.object(s => { "name": s.field("Name", S.string), "email": s.field("Email", S.string), @@ -564,26 +564,26 @@ test("Successfully serializes object with mapped field", t => { ) t->Assert.deepEqual( - {"name": "Dmitry", "email": "dzakh.dev@gmail.com", "age": 21}->S.serializeToUnknownWith(struct), + {"name": "Dmitry", "email": "dzakh.dev@gmail.com", "age": 21}->S.serializeToUnknownWith(schema), Ok(%raw(`{"Name":"Dmitry","Email":"dzakh.dev@gmail.com","Age":21}`)), (), ) }) test("Successfully parses object transformed to tuple", t => { - let struct = S.object(s => (s.field("boo", S.int), s.field("zoo", S.int))) + let schema = S.object(s => (s.field("boo", S.int), s.field("zoo", S.int))) - t->Assert.deepEqual(%raw(`{boo: 1, zoo: 2}`)->S.parseAnyWith(struct), Ok(1, 2), ()) + t->Assert.deepEqual(%raw(`{boo: 1, zoo: 2}`)->S.parseAnyWith(schema), Ok(1, 2), ()) }) test("Successfully serializes object transformed to tuple", t => { - let struct = S.object(s => (s.field("boo", S.int), s.field("zoo", S.int))) + let schema = S.object(s => (s.field("boo", S.int), s.field("zoo", S.int))) - t->Assert.deepEqual((1, 2)->S.serializeToUnknownWith(struct), Ok(%raw(`{boo: 1, zoo: 2}`)), ()) + t->Assert.deepEqual((1, 2)->S.serializeToUnknownWith(schema), Ok(%raw(`{boo: 1, zoo: 2}`)), ()) }) test("Successfully parses object transformed to nested object", t => { - let struct = S.object(s => + let schema = S.object(s => { "v1": { "boo": s.field("boo", S.int), @@ -593,14 +593,14 @@ test("Successfully parses object transformed to nested object", t => { ) t->Assert.deepEqual( - %raw(`{boo: 1, zoo: 2}`)->S.parseAnyWith(struct), + %raw(`{boo: 1, zoo: 2}`)->S.parseAnyWith(schema), Ok({"v1": {"boo": 1, "zoo": 2}}), (), ) }) test("Successfully serializes object transformed to nested object", t => { - let struct = S.object(s => + let schema = S.object(s => { "v1": { "boo": s.field("boo", S.int), @@ -610,50 +610,50 @@ test("Successfully serializes object transformed to nested object", t => { ) t->Assert.deepEqual( - {"v1": {"boo": 1, "zoo": 2}}->S.serializeToUnknownWith(struct), + {"v1": {"boo": 1, "zoo": 2}}->S.serializeToUnknownWith(schema), Ok(%raw(`{boo: 1, zoo: 2}`)), (), ) }) test("Successfully parses object transformed to nested tuple", t => { - let struct = S.object(s => + let schema = S.object(s => { "v1": (s.field("boo", S.int), s.field("zoo", S.int)), } ) - t->Assert.deepEqual(%raw(`{boo: 1, zoo: 2}`)->S.parseAnyWith(struct), Ok({"v1": (1, 2)}), ()) + t->Assert.deepEqual(%raw(`{boo: 1, zoo: 2}`)->S.parseAnyWith(schema), Ok({"v1": (1, 2)}), ()) }) test("Successfully serializes object transformed to nested tuple", t => { - let struct = S.object(s => + let schema = S.object(s => { "v1": (s.field("boo", S.int), s.field("zoo", S.int)), } ) t->Assert.deepEqual( - {"v1": (1, 2)}->S.serializeToUnknownWith(struct), + {"v1": (1, 2)}->S.serializeToUnknownWith(schema), Ok(%raw(`{boo: 1, zoo: 2}`)), (), ) }) test("Successfully parses object with only one field returned from transformer", t => { - let struct = S.object(s => s.field("field", S.bool)) + let schema = S.object(s => s.field("field", S.bool)) - t->Assert.deepEqual(%raw(`{"field": true}`)->S.parseAnyWith(struct), Ok(true), ()) + t->Assert.deepEqual(%raw(`{"field": true}`)->S.parseAnyWith(schema), Ok(true), ()) }) test("Successfully serializes object with only one field returned from transformer", t => { - let struct = S.object(s => s.field("field", S.bool)) + let schema = S.object(s => s.field("field", S.bool)) - t->Assert.deepEqual(true->S.serializeToUnknownWith(struct), Ok(%raw(`{"field": true}`)), ()) + t->Assert.deepEqual(true->S.serializeToUnknownWith(schema), Ok(%raw(`{"field": true}`)), ()) }) test("Successfully parses object transformed to the one with hardcoded fields", t => { - let struct = S.object(s => + let schema = S.object(s => { "hardcoded": false, "field": s.field("field", S.bool), @@ -661,7 +661,7 @@ test("Successfully parses object transformed to the one with hardcoded fields", ) t->Assert.deepEqual( - %raw(`{"field": true}`)->S.parseAnyWith(struct), + %raw(`{"field": true}`)->S.parseAnyWith(schema), Ok({ "hardcoded": false, "field": true, @@ -671,7 +671,7 @@ test("Successfully parses object transformed to the one with hardcoded fields", }) test("Successfully serializes object transformed to the one with hardcoded fields", t => { - let struct = S.object(s => + let schema = S.object(s => { "hardcoded": false, "field": s.field("field", S.bool), @@ -682,30 +682,30 @@ test("Successfully serializes object transformed to the one with hardcoded field { "hardcoded": false, "field": true, - }->S.serializeToUnknownWith(struct), + }->S.serializeToUnknownWith(schema), Ok(%raw(`{"field": true}`)), (), ) }) test("Successfully parses object transformed to variant", t => { - let struct = S.object(s => #VARIANT(s.field("field", S.bool))) + let schema = S.object(s => #VARIANT(s.field("field", S.bool))) - t->Assert.deepEqual(%raw(`{"field": true}`)->S.parseAnyWith(struct), Ok(#VARIANT(true)), ()) + t->Assert.deepEqual(%raw(`{"field": true}`)->S.parseAnyWith(schema), Ok(#VARIANT(true)), ()) }) test("Successfully serializes object transformed to variant", t => { - let struct = S.object(s => #VARIANT(s.field("field", S.bool))) + let schema = S.object(s => #VARIANT(s.field("field", S.bool))) t->Assert.deepEqual( - #VARIANT(true)->S.serializeToUnknownWith(struct), + #VARIANT(true)->S.serializeToUnknownWith(schema), Ok(%raw(`{"field": true}`)), (), ) }) test("Successfully parses object from benchmark", t => { - let struct = S.object(s => + let schema = S.object(s => { "number": s.field("number", S.float), "negNumber": s.field("negNumber", S.float), @@ -741,7 +741,7 @@ test("Successfully parses object from benchmark", t => { num: 1, bool: false, }, - })`)->S.parseAnyWith(struct), + })`)->S.parseAnyWith(schema), Ok({ "number": 1., "negNumber": -1., @@ -760,7 +760,7 @@ test("Successfully parses object from benchmark", t => { }) test("Successfully parses strict object from benchmark", t => { - let struct = S.object(s => + let schema = S.object(s => { "number": s.field("number", S.float), "negNumber": s.field("negNumber", S.float), @@ -796,7 +796,7 @@ test("Successfully parses strict object from benchmark", t => { num: 1, bool: false, }, - })`)->S.parseAnyWith(struct), + })`)->S.parseAnyWith(schema), Ok({ "number": 1., "negNumber": -1., @@ -815,7 +815,7 @@ test("Successfully parses strict object from benchmark", t => { }) test("Successfully serializes object from benchmark", t => { - let struct = S.object(s => + let schema = S.object(s => { "number": s.field("number", S.float), "negNumber": s.field("negNumber", S.float), @@ -850,7 +850,7 @@ test("Successfully serializes object from benchmark", t => { "num": 1., "bool": false, }, - }->S.serializeToUnknownWith(struct), + }->S.serializeToUnknownWith(schema), Ok( %raw(`{ number: 1, @@ -874,7 +874,7 @@ test("Successfully serializes object from benchmark", t => { test("Successfully parses object and serializes it back to the initial data", t => { let any = %raw(`{"Name":"Dmitry","Email":"dzakh.dev@gmail.com","Age":21}`) - let struct = S.object(s => + let schema = S.object(s => { "name": s.field("Name", S.string), "email": s.field("Email", S.string), @@ -883,14 +883,14 @@ test("Successfully parses object and serializes it back to the initial data", t ) t->Assert.deepEqual( - any->S.parseAnyWith(struct)->Result.map(object => object->S.serializeToUnknownWith(struct)), + any->S.parseAnyWith(schema)->Result.map(object => object->S.serializeToUnknownWith(schema)), Ok(Ok(any)), (), ) }) -test("Allows to create object struct with unused fields", t => { - let struct = S.object(s => { +test("Allows to create object schema with unused fields", t => { + let schema = S.object(s => { ignore(s.field("unused", S.string)) { "field": s.field("field", S.string), @@ -898,13 +898,13 @@ test("Allows to create object struct with unused fields", t => { }) t->Assert.deepEqual( - %raw(`{"field": "foo", "unused": "bar"}`)->S.parseAnyWith(struct), + %raw(`{"field": "foo", "unused": "bar"}`)->S.parseAnyWith(schema), Ok({"field": "foo"}), (), ) }) -test("Fails to create object struct with single field defined multiple times", t => { +test("Fails to create object schema with single field defined multiple times", t => { t->Assert.throws( () => { S.object( @@ -916,14 +916,14 @@ test("Fails to create object struct with single field defined multiple times", t ) }, ~expectations={ - message: `[rescript-struct] The field "field" is defined multiple times. If you want to duplicate the field, use S.transform instead.`, + message: `[rescript-schema] The field "field" is defined multiple times. If you want to duplicate the field, use S.transform instead.`, }, (), ) }) -test("Successfully parses object struct with single field registered multiple times", t => { - let struct = S.object(s => { +test("Successfully parses object schema with single field registered multiple times", t => { + let schema = S.object(s => { let field = s.field("field", S.string) { "field1": field, @@ -931,14 +931,14 @@ test("Successfully parses object struct with single field registered multiple ti } }) t->Assert.deepEqual( - %raw(`{"field": "foo"}`)->S.parseAnyWith(struct), + %raw(`{"field": "foo"}`)->S.parseAnyWith(schema), Ok({"field1": "foo", "field2": "foo"}), (), ) }) -test("Fails to serialize object struct with single field registered multiple times", t => { - let struct = S.object(s => { +test("Fails to serialize object schema with single field registered multiple times", t => { + let schema = S.object(s => { let field = s.field("field", S.string) { "field1": field, @@ -946,7 +946,7 @@ test("Fails to serialize object struct with single field registered multiple tim } }) t->Assert.deepEqual( - {"field1": "foo", "field2": "foo"}->S.serializeToUnknownWith(struct), + {"field1": "foo", "field2": "foo"}->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({ @@ -960,8 +960,8 @@ test("Fails to serialize object struct with single field registered multiple tim ) }) -test("Object struct parsing checks order", t => { - let struct = S.object(s => { +test("Object schema parsing checks order", t => { + let schema = S.object(s => { s.tag("tag", "value") { "key": s.field("key", S.literal("value")), @@ -970,10 +970,10 @@ test("Object struct parsing checks order", t => { // Type check should be the first t->Assert.deepEqual( - %raw(`"foo"`)->S.parseAnyWith(struct), + %raw(`"foo"`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`"foo"`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`"foo"`)}), operation: Parsing, path: S.Path.empty, }), @@ -983,7 +983,7 @@ test("Object struct parsing checks order", t => { // Tag check should be the second t->Assert.deepEqual( %raw(`{tag: "wrong", key: "wrong", unknownKey: "value", unknownKey2: "value"}`)->S.parseAnyWith( - struct, + schema, ), Error( U.error({ @@ -997,7 +997,7 @@ test("Object struct parsing checks order", t => { // Field check should be the third t->Assert.deepEqual( %raw(`{tag: "value", key: "wrong", unknownKey: "value", unknownKey2: "value"}`)->S.parseAnyWith( - struct, + schema, ), Error( U.error({ @@ -1011,14 +1011,14 @@ test("Object struct parsing checks order", t => { // Unknown keys check should be the last t->Assert.deepEqual( %raw(`{tag: "value", key: "value", unknownKey: "value2", unknownKey2: "value2"}`)->S.parseAnyWith( - struct, + schema, ), Error(U.error({code: ExcessField("unknownKey"), operation: Parsing, path: S.Path.empty})), (), ) // Parses valid t->Assert.deepEqual( - %raw(`{tag: "value", key: "value"}`)->S.parseAnyWith(struct), + %raw(`{tag: "value", key: "value"}`)->S.parseAnyWith(schema), Ok({ "key": "value", }), @@ -1028,7 +1028,7 @@ test("Object struct parsing checks order", t => { module Compiled = { test("Compiled parse code snapshot for simple object", t => { - let struct = S.object(s => + let schema = S.object(s => { "foo": s.field("foo", S.string), "bar": s.field("bar", S.bool), @@ -1036,14 +1036,14 @@ module Compiled = { ) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1;if(!i||i.constructor!==Object){e[2](i)}v0=i["foo"];if(typeof v0!=="string"){e[0](v0)}v1=i["bar"];if(typeof v1!=="boolean"){e[1](v1)}return {"foo":v0,"bar":v1,}}`, ) }) test("Compiled parse code snapshot for simple object with async", t => { - let struct = S.object(s => + let schema = S.object(s => { "foo": s.field( "foo", @@ -1054,25 +1054,25 @@ module Compiled = { ) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1,v2;if(!i||i.constructor!==Object){e[2](i)}v0=e[0](i["foo"]);v1=i["bar"];if(typeof v1!=="boolean"){e[1](v1)}v2=()=>Promise.all([v0()]).then(([v0])=>({"foo":v0,"bar":v1,}));return v2}`, ) }) test("Compiled serialize code snapshot for simple object", t => { - let struct = S.object(s => + let schema = S.object(s => { "foo": s.field("foo", S.string), "bar": s.field("bar", S.bool), } ) - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{return {"foo":i["foo"],"bar":i["bar"],}}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{return {"foo":i["foo"],"bar":i["bar"],}}`) }) test("Compiled parse code snapshot for simple object with strict unknown keys", t => { - let struct = S.object(s => + let schema = S.object(s => { "foo": s.field("foo", S.string), "bar": s.field("bar", S.bool), @@ -1080,27 +1080,27 @@ module Compiled = { )->S.Object.strict t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1,v2;if(!i||i.constructor!==Object){e[3](i)}v1=i["foo"];if(typeof v1!=="string"){e[1](v1)}v2=i["bar"];if(typeof v2!=="boolean"){e[2](v2)}for(v0 in i){if(v0!=="foo"&&v0!=="bar"){e[0](v0)}}return {"foo":v1,"bar":v2,}}`, ) }) test("Compiled serialize code snapshot for simple object with strict unknown keys", t => { - let struct = S.object(s => + let schema = S.object(s => { "foo": s.field("foo", S.string), "bar": s.field("bar", S.bool), } )->S.Object.strict - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{return {"foo":i["foo"],"bar":i["bar"],}}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{return {"foo":i["foo"],"bar":i["bar"],}}`) }) test( "Compiled parse code snapshot for simple object with strict unknown keys, renamed fields, constants and discriminants", t => { - let struct = S.object(s => { + let schema = S.object(s => { s.tag("tag", 0) { "foo": s.field("FOO", S.string), @@ -1110,7 +1110,7 @@ module Compiled = { })->S.Object.strict t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1,v2,v3;if(!i||i.constructor!==Object){e[6](i)}v3=i["tag"];v3===e[4]||e[5](v3);v1=i["FOO"];if(typeof v1!=="string"){e[1](v1)}v2=i["BAR"];if(typeof v2!=="boolean"){e[2](v2)}for(v0 in i){if(v0!=="tag"&&v0!=="FOO"&&v0!=="BAR"){e[0](v0)}}return {"foo":v1,"bar":v2,"zoo":e[3],}}`, ) @@ -1120,7 +1120,7 @@ module Compiled = { test( "Compiled serialize code snapshot for simple object with strict unknown keys, renamed fields, constants and discriminants", t => { - let struct = S.object(s => { + let schema = S.object(s => { s.tag("tag", 0) { "foo": s.field("FOO", S.string), @@ -1130,7 +1130,7 @@ module Compiled = { })->S.Object.strict t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{if(i["zoo"]!==e[0]){e[1](i["zoo"])}return {"FOO":i["foo"],"BAR":i["bar"],"tag":e[2],}}`, ) @@ -1139,19 +1139,19 @@ module Compiled = { } test( - "Works with object struct used multiple times as a child struct. See: https://github.com/DZakh/rescript-struct/issues/63", + "Works with object schema used multiple times as a child schema. See: https://github.com/DZakh/rescript-schema/issues/63", t => { - let appVersionSpecStruct = S.object(s => + let appVersionSpecSchema = S.object(s => { "current": s.field("current", S.string), "minimum": s.field("minimum", S.string), } ) - let appVersionsStruct = S.object(s => + let appVersionsSchema = S.object(s => { - "ios": s.field("ios", appVersionSpecStruct), - "android": s.field("android", appVersionSpecStruct), + "ios": s.field("ios", appVersionSpecSchema), + "android": s.field("android", appVersionSpecSchema), } ) @@ -1160,10 +1160,10 @@ test( "android": {"current": "1.2", "minimum": "1.1"}, } - let value = appVersions->S.parseAnyOrRaiseWith(appVersionsStruct) + let value = appVersions->S.parseAnyOrRaiseWith(appVersionsSchema) t->Assert.deepEqual(value, appVersions, ()) - let data = appVersions->S.serializeOrRaiseWith(appVersionsStruct) + let data = appVersions->S.serializeOrRaiseWith(appVersionsSchema) t->Assert.deepEqual(data, appVersions->Obj.magic, ()) }, ) diff --git a/packages/tests/src/core/S_object_withoutDeclaredFields_test.res b/packages/tests/src/core/S_object_withoutDeclaredFields_test.res index 4e9ec6dd..7d2a4a38 100644 --- a/packages/tests/src/core/S_object_withoutDeclaredFields_test.res +++ b/packages/tests/src/core/S_object_withoutDeclaredFields_test.res @@ -1,28 +1,28 @@ open Ava test("Successfully parses empty object", t => { - let struct = S.object(_ => ()) + let schema = S.object(_ => ()) - t->Assert.deepEqual(%raw(`{}`)->S.parseAnyWith(struct), Ok(), ()) + t->Assert.deepEqual(%raw(`{}`)->S.parseAnyWith(schema), Ok(), ()) }) test("Successfully parses object with excess keys", t => { - let struct = S.object(_ => ()) + let schema = S.object(_ => ()) - t->Assert.deepEqual(%raw(`{field:"bar"}`)->S.parseAnyWith(struct), Ok(), ()) + t->Assert.deepEqual(%raw(`{field:"bar"}`)->S.parseAnyWith(schema), Ok(), ()) }) test("Successfully parses empty object when UnknownKeys are strict", t => { - let struct = S.object(_ => ())->S.Object.strict + let schema = S.object(_ => ())->S.Object.strict - t->Assert.deepEqual(%raw(`{}`)->S.parseAnyWith(struct), Ok(), ()) + t->Assert.deepEqual(%raw(`{}`)->S.parseAnyWith(schema), Ok(), ()) }) test("Fails to parse object with excess keys when UnknownKeys are strict", t => { - let struct = S.object(_ => ())->S.Object.strict + let schema = S.object(_ => ())->S.Object.strict t->Assert.deepEqual( - %raw(`{field:"bar"}`)->S.parseAnyWith(struct), + %raw(`{field:"bar"}`)->S.parseAnyWith(schema), Error(U.error({code: ExcessField("field"), operation: Parsing, path: S.Path.empty})), (), ) @@ -30,26 +30,26 @@ test("Fails to parse object with excess keys when UnknownKeys are strict", t => test("Successfully parses object with excess keys and returns transformed value", t => { let transformedValue = {"bas": true} - let struct = S.object(_ => transformedValue) + let schema = S.object(_ => transformedValue) - t->Assert.deepEqual(%raw(`{field:"bar"}`)->S.parseAnyWith(struct), Ok(transformedValue), ()) + t->Assert.deepEqual(%raw(`{field:"bar"}`)->S.parseAnyWith(schema), Ok(transformedValue), ()) }) test("Successfully serializes transformed value to empty object", t => { let transformedValue = {"bas": true} - let struct = S.object(_ => transformedValue) + let schema = S.object(_ => transformedValue) - t->Assert.deepEqual(transformedValue->S.serializeToUnknownWith(struct), Ok(%raw("{}")), ()) + t->Assert.deepEqual(transformedValue->S.serializeToUnknownWith(schema), Ok(%raw("{}")), ()) }) test("Fails to parse array data", t => { - let struct = S.object(_ => ()) + let schema = S.object(_ => ()) t->Assert.deepEqual( - %raw(`[]`)->S.parseAnyWith(struct), + %raw(`[]`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`[]`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`[]`)}), operation: Parsing, path: S.Path.empty, }), diff --git a/packages/tests/src/core/S_option_test.res b/packages/tests/src/core/S_option_test.res index bc8ee78e..740d630d 100644 --- a/packages/tests/src/core/S_option_test.res +++ b/packages/tests/src/core/S_option_test.res @@ -8,19 +8,19 @@ module Common = { let factory = () => S.option(S.string) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -30,36 +30,36 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(i!==void 0&&(typeof i!=="string")){e[0](i)}if(i!==void 0){v0=i}else{v0=void 0}return v0}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = S.option(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) + let schema = S.option(S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(i!==void 0){let v1;v1=e[0](i);v0=v1}else{v0=()=>Promise.resolve(void 0)}return v0}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;if(i!==void 0){v0=e[0](i)}else{v0=void 0}return v0}`, ) @@ -67,19 +67,19 @@ module Common = { } test("Successfully parses primitive", t => { - let struct = S.option(S.bool) + let schema = S.option(S.bool) - t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(struct), Ok(Some(true)), ()) + t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseAnyWith(schema), Ok(Some(true)), ()) }) test("Fails to parse JS null", t => { - let struct = S.option(S.bool) + let schema = S.option(S.bool) t->Assert.deepEqual( - %raw(`null`)->S.parseAnyWith(struct), + %raw(`null`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`null`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`null`)}), operation: Parsing, path: S.Path.empty, }), @@ -88,14 +88,14 @@ test("Fails to parse JS null", t => { ) }) -test("Fails to parse JS undefined when struct doesn't allow optional data", t => { - let struct = S.bool +test("Fails to parse JS undefined when schema doesn't allow optional data", t => { + let schema = S.bool t->Assert.deepEqual( - %raw(`undefined`)->S.parseAnyWith(struct), + %raw(`undefined`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`undefined`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`undefined`)}), operation: Parsing, path: S.Path.empty, }), @@ -105,15 +105,15 @@ test("Fails to parse JS undefined when struct doesn't allow optional data", t => }) test("Parses option nested in null as None instead of Some(None)", t => { - let struct = S.null(S.option(S.bool)) + let schema = S.null(S.option(S.bool)) - t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(struct), Ok(None), ()) - t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(struct), Ok(None), ()) + t->Assert.deepEqual(%raw(`null`)->S.parseAnyWith(schema), Ok(None), ()) + t->Assert.deepEqual(%raw(`undefined`)->S.parseAnyWith(schema), Ok(None), ()) }) test("Serializes Some(None) to undefined for option nested in null", t => { - let struct = S.null(S.option(S.bool)) + let schema = S.null(S.option(S.bool)) - t->Assert.deepEqual(Some(None)->S.serializeToUnknownWith(struct), Ok(%raw(`undefined`)), ()) - t->Assert.deepEqual(None->S.serializeToUnknownWith(struct), Ok(%raw(`null`)), ()) + t->Assert.deepEqual(Some(None)->S.serializeToUnknownWith(schema), Ok(%raw(`undefined`)), ()) + t->Assert.deepEqual(None->S.serializeToUnknownWith(schema), Ok(%raw(`null`)), ()) }) diff --git a/packages/tests/src/core/S_parseAnyAsyncInStepsWith_test.res b/packages/tests/src/core/S_parseAnyAsyncInStepsWith_test.res index cc0406d6..10fd7419 100644 --- a/packages/tests/src/core/S_parseAnyAsyncInStepsWith_test.res +++ b/packages/tests/src/core/S_parseAnyAsyncInStepsWith_test.res @@ -13,23 +13,23 @@ let invalidAsyncRefine = S.transform(_, s => { }) asyncTest("Successfully parses without asyncRefine", t => { - let struct = S.string + let schema = S.string ( - %raw(`"Hello world!"`)->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + %raw(`"Hello world!"`)->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok("Hello world!"), ()) }) }) test("Fails to parse without asyncRefine", t => { - let struct = S.string + let schema = S.string t->Assert.deepEqual( - %raw(`123`)->S.parseAnyAsyncInStepsWith(struct), + %raw(`123`)->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`123`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`123`)}), operation: Parsing, path: S.Path.empty, }), @@ -39,20 +39,20 @@ test("Fails to parse without asyncRefine", t => { }) asyncTest("Successfully parses with validAsyncRefine", t => { - let struct = S.string->validAsyncRefine + let schema = S.string->validAsyncRefine ( - %raw(`"Hello world!"`)->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + %raw(`"Hello world!"`)->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok("Hello world!"), ()) }) }) asyncTest("Fails to parse with invalidAsyncRefine", t => { - let struct = S.string->invalidAsyncRefine + let schema = S.string->invalidAsyncRefine ( - %raw(`"Hello world!"`)->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + %raw(`"Hello world!"`)->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( result, @@ -70,7 +70,7 @@ asyncTest("Fails to parse with invalidAsyncRefine", t => { module Object = { asyncTest("[Object] Successfully parses", t => { - let struct = S.object(s => + let schema = S.object(s => { "k1": s.field("k1", S.int), "k2": s.field("k2", S.int->validAsyncRefine), @@ -84,7 +84,7 @@ module Object = { "k2": 2, "k3": 3, } - ->S.parseAnyAsyncInStepsWith(struct) + ->S.parseAnyAsyncInStepsWith(schema) ->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( @@ -100,7 +100,7 @@ module Object = { }) asyncTest("[Object] Successfully parses async object in array", t => { - let struct = S.array( + let schema = S.array( S.object(s => { "k1": s.field("k1", S.int), @@ -123,7 +123,7 @@ module Object = { "k3": 6, }, ] - ->S.parseAnyAsyncInStepsWith(struct) + ->S.parseAnyAsyncInStepsWith(schema) ->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( @@ -146,7 +146,7 @@ module Object = { }) asyncTest("[Object] Keeps fields in the correct order", t => { - let struct = S.object(s => + let schema = S.object(s => { "k1": s.field("k1", S.int), "k2": s.field("k2", S.int->validAsyncRefine), @@ -160,7 +160,7 @@ module Object = { "k2": 2, "k3": 3, } - ->S.parseAnyAsyncInStepsWith(struct) + ->S.parseAnyAsyncInStepsWith(schema) ->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( @@ -172,7 +172,7 @@ module Object = { }) asyncTest("[Object] Successfully parses with valid async discriminant", t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("discriminant", S.literal(true)->validAsyncRefine)) { "k1": s.field("k1", S.int), @@ -188,7 +188,7 @@ module Object = { "k2": 2, "k3": 3, } - ->S.parseAnyAsyncInStepsWith(struct) + ->S.parseAnyAsyncInStepsWith(schema) ->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( @@ -204,7 +204,7 @@ module Object = { }) asyncTest("[Object] Fails to parse with invalid async discriminant", t => { - let struct = S.object(s => { + let schema = S.object(s => { ignore(s.field("discriminant", S.literal(true)->invalidAsyncRefine)) { "k1": s.field("k1", S.int), @@ -220,7 +220,7 @@ module Object = { "k2": 2, "k3": 3, } - ->S.parseAnyAsyncInStepsWith(struct) + ->S.parseAnyAsyncInStepsWith(schema) ->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( @@ -238,11 +238,11 @@ module Object = { }) test("[Object] Returns sync error when fails to parse sync part of async item", t => { - let invalidStruct = S.int->validAsyncRefine - let struct = S.object(s => + let invalidSchema = S.int->validAsyncRefine + let schema = S.object(s => { "k1": s.field("k1", S.int), - "k2": s.field("k2", invalidStruct), + "k2": s.field("k2", invalidSchema), "k3": s.field("k3", S.int), } ) @@ -252,10 +252,10 @@ module Object = { "k1": 1, "k2": true, "k3": 3, - }->S.parseAnyAsyncInStepsWith(struct), + }->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: invalidStruct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: invalidSchema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.fromArray(["k2"]), }), @@ -265,7 +265,7 @@ module Object = { }) test("[Object] Parses sync items first, and then starts parsing async ones", t => { - let struct = S.object(s => + let schema = S.object(s => { "k1": s.field("k1", S.int), "k2": s.field("k2", S.int->invalidAsyncRefine), @@ -278,7 +278,7 @@ module Object = { "k1": 1, "k2": 2, "k3": 3, - }->S.parseAnyAsyncInStepsWith(struct), + }->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ code: OperationFailed("Sync user error"), @@ -293,7 +293,7 @@ module Object = { test("[Object] Parses async items in parallel", t => { let actionCounter = ref(0) - let struct = S.object(s => + let schema = S.object(s => { "k1": s.field( "k1", @@ -324,14 +324,14 @@ module Object = { "k1": 1, "k2": 2, } - ->S.parseAnyAsyncWith(struct) + ->S.parseAnyAsyncWith(schema) ->ignore t->Assert.deepEqual(actionCounter.contents, 2, ()) }) asyncTest("[Object] Doesn't wait for pending async items when fails to parse", t => { - let struct = S.object(s => + let schema = S.object(s => { "k1": s.field( "k1", @@ -350,7 +350,7 @@ module Object = { "k1": 1, "k2": 2, } - ->S.parseAnyAsyncInStepsWith(struct) + ->S.parseAnyAsyncInStepsWith(schema) ->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( @@ -370,24 +370,24 @@ module Object = { module Tuple = { asyncTest("[Tuple] Successfully parses", t => { - let struct = S.tuple3(S.int, S.int->validAsyncRefine, S.int) + let schema = S.tuple3(S.int, S.int->validAsyncRefine, S.int) ( - [1, 2, 3]->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + [1, 2, 3]->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(1, 2, 3), ()) }) }) test("[Tuple] Returns sync error when fails to parse sync part of async item", t => { - let invalidStruct = S.int->validAsyncRefine - let struct = S.tuple3(S.int, invalidStruct, S.int) + let invalidSchema = S.int->validAsyncRefine + let schema = S.tuple3(S.int, invalidSchema, S.int) t->Assert.deepEqual( - %raw(`[1, true, 3]`)->S.parseAnyAsyncInStepsWith(struct), + %raw(`[1, true, 3]`)->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: invalidStruct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: invalidSchema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.fromArray(["1"]), }), @@ -397,14 +397,14 @@ module Tuple = { }) test("[Tuple] Parses sync items first, and then starts parsing async ones", t => { - let struct = S.tuple3( + let schema = S.tuple3( S.int, S.int->invalidSyncRefine->invalidAsyncRefine, S.int->invalidSyncRefine, ) t->Assert.deepEqual( - [1, 2, 3]->S.parseAnyAsyncInStepsWith(struct), + [1, 2, 3]->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ code: OperationFailed("Sync user error"), @@ -419,7 +419,7 @@ module Tuple = { test("[Tuple] Parses async items in parallel", t => { let actionCounter = ref(0) - let struct = S.tuple2( + let schema = S.tuple2( S.int->S.transform(_ => { asyncParser: _ => () => { actionCounter.contents = actionCounter.contents + 1 @@ -434,18 +434,18 @@ module Tuple = { }), ) - [1, 2]->S.parseAnyAsyncWith(struct)->ignore + [1, 2]->S.parseAnyAsyncWith(schema)->ignore t->Assert.deepEqual(actionCounter.contents, 2, ()) }) asyncTest("[Tuple] Doesn't wait for pending async items when fails to parse", t => { - let struct = S.tuple2( + let schema = S.tuple2( S.int->S.transform(_ => {asyncParser: _ => () => unresolvedPromise}), S.int->invalidAsyncRefine, ) - ([1, 2]->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + ([1, 2]->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual( result, Error( @@ -463,26 +463,26 @@ module Tuple = { module Union = { asyncTest("[Union] Successfully parses", t => { - let struct = S.union([S.literal(1), S.literal(2)->validAsyncRefine, S.literal(3)]) + let schema = S.union([S.literal(1), S.literal(2)->validAsyncRefine, S.literal(3)]) Promise.all([ - (1->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (1->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(1), ()) }), - (2->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (2->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(2), ()) }), - (3->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (3->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(3), ()) }), ])->Promise.thenResolve(_ => ()) }) asyncTest("[Union] Doesn't return sync error when fails to parse sync part of async item", t => { - let struct = S.union([S.literal(1), S.literal(2)->validAsyncRefine, S.literal(3)]) + let schema = S.union([S.literal(1), S.literal(2)->validAsyncRefine, S.literal(3)]) let input = %raw("true") - (input->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (input->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual( result, Error( @@ -516,7 +516,7 @@ module Union = { test("[Union] Parses async items in parallel", t => { let actionCounter = ref(0) - let struct = S.union([ + let schema = S.union([ S.literal(2)->S.transform(_ => { asyncParser: _ => () => { actionCounter.contents = actionCounter.contents + 1 @@ -531,7 +531,7 @@ module Union = { }), ]) - 2->S.parseAnyAsyncWith(struct)->ignore + 2->S.parseAnyAsyncWith(schema)->ignore t->Assert.deepEqual(actionCounter.contents, 2, ()) }) @@ -539,24 +539,24 @@ module Union = { module Array = { asyncTest("[Array] Successfully parses", t => { - let struct = S.array(S.int->validAsyncRefine) + let schema = S.array(S.int->validAsyncRefine) ( - [1, 2, 3]->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + [1, 2, 3]->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok([1, 2, 3]), ()) }) }) test("[Array] Returns sync error when fails to parse sync part of async item", t => { - let invalidStruct = S.int->validAsyncRefine - let struct = S.array(invalidStruct) + let invalidSchema = S.int->validAsyncRefine + let schema = S.array(invalidSchema) t->Assert.deepEqual( - %raw(`[1, 2, true]`)->S.parseAnyAsyncInStepsWith(struct), + %raw(`[1, 2, true]`)->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: invalidStruct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: invalidSchema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.fromArray(["2"]), }), @@ -568,7 +568,7 @@ module Array = { test("[Array] Parses async items in parallel", t => { let actionCounter = ref(0) - let struct = S.array( + let schema = S.array( S.int->S.transform(_ => { asyncParser: _ => () => { actionCounter.contents = actionCounter.contents + 1 @@ -577,7 +577,7 @@ module Array = { }), ) - [1, 2]->S.parseAnyAsyncWith(struct)->ignore + [1, 2]->S.parseAnyAsyncWith(schema)->ignore t->Assert.deepEqual(actionCounter.contents, 2, ()) }) @@ -585,7 +585,7 @@ module Array = { asyncTest("[Array] Doesn't wait for pending async items when fails to parse", t => { let actionCounter = ref(0) - let struct = S.array( + let schema = S.array( S.int->S.transform(s => { asyncParser: _ => () => { actionCounter.contents = actionCounter.contents + 1 @@ -599,7 +599,7 @@ module Array = { ) ( - [1, 2, 3]->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + [1, 2, 3]->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( result, @@ -618,24 +618,24 @@ module Array = { module Dict = { asyncTest("[Dict] Successfully parses", t => { - let struct = S.dict(S.int->validAsyncRefine) + let schema = S.dict(S.int->validAsyncRefine) ( - {"k1": 1, "k2": 2, "k3": 3}->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + {"k1": 1, "k2": 2, "k3": 3}->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(Dict.fromArray([("k1", 1), ("k2", 2), ("k3", 3)])), ()) }) }) test("[Dict] Returns sync error when fails to parse sync part of async item", t => { - let invalidStruct = S.int->validAsyncRefine - let struct = S.dict(invalidStruct) + let invalidSchema = S.int->validAsyncRefine + let schema = S.dict(invalidSchema) t->Assert.deepEqual( - {"k1": 1, "k2": 2, "k3": true}->S.parseAnyAsyncInStepsWith(struct), + {"k1": 1, "k2": 2, "k3": true}->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: invalidStruct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: invalidSchema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.fromArray(["k3"]), }), @@ -647,7 +647,7 @@ module Dict = { test("[Dict] Parses async items in parallel", t => { let actionCounter = ref(0) - let struct = S.dict( + let schema = S.dict( S.int->S.transform(_ => { asyncParser: _ => () => { actionCounter.contents = actionCounter.contents + 1 @@ -656,7 +656,7 @@ module Dict = { }), ) - {"k1": 1, "k2": 2}->S.parseAnyAsyncWith(struct)->ignore + {"k1": 1, "k2": 2}->S.parseAnyAsyncWith(schema)->ignore t->Assert.deepEqual(actionCounter.contents, 2, ()) }) @@ -664,7 +664,7 @@ module Dict = { asyncTest("[Dict] Doesn't wait for pending async items when fails to parse", t => { let actionCounter = ref(0) - let struct = S.dict( + let schema = S.dict( S.int->S.transform(s => { asyncParser: _ => () => { actionCounter.contents = actionCounter.contents + 1 @@ -678,7 +678,7 @@ module Dict = { ) ( - {"k1": 1, "k2": 2, "k3": 3}->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + {"k1": 1, "k2": 2, "k3": 3}->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual( result, @@ -697,14 +697,14 @@ module Dict = { module Null = { asyncTest("[Null] Successfully parses", t => { - let struct = S.null(S.int->validAsyncRefine) + let schema = S.null(S.int->validAsyncRefine) Promise.all([ - (1->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (1->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(Some(1)), ()) }), ( - %raw(`null`)->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + %raw(`null`)->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(None), ()) }), @@ -712,9 +712,9 @@ module Null = { }) asyncTest("[Null] Fails to parse with invalid async refine", t => { - let struct = S.null(S.int->invalidAsyncRefine) + let schema = S.null(S.int->invalidAsyncRefine) - (1->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (1->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual( result, Error( @@ -730,13 +730,13 @@ module Null = { }) test("[Null] Returns sync error when fails to parse sync part of async item", t => { - let struct = S.null(S.int->validAsyncRefine) + let schema = S.null(S.int->validAsyncRefine) t->Assert.deepEqual( - true->S.parseAnyAsyncInStepsWith(struct), + true->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.empty, }), @@ -748,14 +748,14 @@ module Null = { module Option = { asyncTest("[Option] Successfully parses", t => { - let struct = S.option(S.int->validAsyncRefine) + let schema = S.option(S.int->validAsyncRefine) Promise.all([ - (1->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (1->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(Some(1)), ()) }), ( - %raw(`undefined`)->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + %raw(`undefined`)->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(None), ()) }), @@ -763,9 +763,9 @@ module Option = { }) asyncTest("[Option] Fails to parse with invalid async refine", t => { - let struct = S.option(S.int->invalidAsyncRefine) + let schema = S.option(S.int->invalidAsyncRefine) - (1->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (1->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual( result, Error( @@ -781,13 +781,13 @@ module Option = { }) test("[Option] Returns sync error when fails to parse sync part of async item", t => { - let struct = S.option(S.int->validAsyncRefine) + let schema = S.option(S.int->validAsyncRefine) t->Assert.deepEqual( - true->S.parseAnyAsyncInStepsWith(struct), + true->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.empty, }), @@ -799,14 +799,14 @@ module Option = { module Defaulted = { asyncTest("[Default] Successfully parses", t => { - let struct = S.int->validAsyncRefine->validAsyncRefine->S.option->S.Option.getOrWith(() => 10) + let schema = S.int->validAsyncRefine->validAsyncRefine->S.option->S.Option.getOrWith(() => 10) Promise.all([ - (1->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (1->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(1), ()) }), ( - %raw(`undefined`)->S.parseAnyAsyncInStepsWith(struct)->Result.getExn + %raw(`undefined`)->S.parseAnyAsyncInStepsWith(schema)->Result.getExn )()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(10), ()) }), @@ -814,9 +814,9 @@ module Defaulted = { }) asyncTest("[Default] Fails to parse with invalid async refine", t => { - let struct = S.int->invalidAsyncRefine->S.option->S.Option.getOrWith(() => 10) + let schema = S.int->invalidAsyncRefine->S.option->S.Option.getOrWith(() => 10) - (1->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + (1->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual( result, Error( @@ -833,13 +833,13 @@ module Defaulted = { }) test("[Default] Returns sync error when fails to parse sync part of async item", t => { - let struct = S.int->validAsyncRefine->S.option->S.Option.getOrWith(() => 10) + let schema = S.int->validAsyncRefine->S.option->S.Option.getOrWith(() => 10) t->Assert.deepEqual( - true->S.parseAnyAsyncInStepsWith(struct), + true->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.empty, }), @@ -851,17 +851,17 @@ module Defaulted = { module Json = { asyncTest("[JsonString] Successfully parses", t => { - let struct = S.jsonString(S.int->validAsyncRefine) + let schema = S.jsonString(S.int->validAsyncRefine) - ("1"->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + ("1"->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok(1), ()) }) }) asyncTest("[JsonString] Fails to parse with invalid async refine", t => { - let struct = S.jsonString(S.int->invalidAsyncRefine) + let schema = S.jsonString(S.int->invalidAsyncRefine) - ("1"->S.parseAnyAsyncInStepsWith(struct)->Result.getExn)()->Promise.thenResolve(result => { + ("1"->S.parseAnyAsyncInStepsWith(schema)->Result.getExn)()->Promise.thenResolve(result => { t->Assert.deepEqual( result, Error( @@ -878,14 +878,14 @@ module Json = { }) test("[JsonString] Returns sync error when fails to parse sync part of async item", t => { - let invalidStruct = S.int->validAsyncRefine - let struct = S.jsonString(invalidStruct) + let invalidSchema = S.int->validAsyncRefine + let schema = S.jsonString(invalidSchema) t->Assert.deepEqual( - "true"->S.parseAnyAsyncInStepsWith(struct), + "true"->S.parseAnyAsyncInStepsWith(schema), Error( U.error({ - code: InvalidType({expected: invalidStruct->S.toUnknown, received: %raw(`true`)}), + code: InvalidType({expected: invalidSchema->S.toUnknown, received: %raw(`true`)}), operation: Parsing, path: S.Path.empty, }), diff --git a/packages/tests/src/core/S_parseAnyOrRaiseWith_test.res b/packages/tests/src/core/S_parseAnyOrRaiseWith_test.res index f4d8d1de..ee199498 100644 --- a/packages/tests/src/core/S_parseAnyOrRaiseWith_test.res +++ b/packages/tests/src/core/S_parseAnyOrRaiseWith_test.res @@ -1,22 +1,22 @@ open Ava test("Successfully parses", t => { - let struct = S.bool + let schema = S.bool - t->Assert.deepEqual(true->S.parseAnyOrRaiseWith(struct), true, ()) + t->Assert.deepEqual(true->S.parseAnyOrRaiseWith(schema), true, ()) }) test("Successfully parses unknown", t => { - let struct = S.unknown + let schema = S.unknown - t->Assert.deepEqual(true->S.parseAnyOrRaiseWith(struct), true->Obj.magic, ()) + t->Assert.deepEqual(true->S.parseAnyOrRaiseWith(schema), true->Obj.magic, ()) }) test("Fails to parse", t => { - let struct = S.bool + let schema = S.bool let maybeError = try { - 123->S.parseAnyOrRaiseWith(struct)->ignore + 123->S.parseAnyOrRaiseWith(schema)->ignore None } catch { | S.Raised(error) => Some(error) @@ -26,7 +26,7 @@ test("Fails to parse", t => { maybeError, Some( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: Obj.magic(123)}), + code: InvalidType({expected: schema->S.toUnknown, received: Obj.magic(123)}), operation: Parsing, path: S.Path.empty, }), diff --git a/packages/tests/src/core/S_parseJsonStringWith_test.res b/packages/tests/src/core/S_parseJsonStringWith_test.res index 6da34816..9542c349 100644 --- a/packages/tests/src/core/S_parseJsonStringWith_test.res +++ b/packages/tests/src/core/S_parseJsonStringWith_test.res @@ -1,21 +1,21 @@ open Ava test("Successfully parses", t => { - let struct = S.bool + let schema = S.bool - t->Assert.deepEqual("true"->S.parseJsonStringWith(struct), Ok(true), ()) + t->Assert.deepEqual("true"->S.parseJsonStringWith(schema), Ok(true), ()) }) test("Successfully parses unknown", t => { - let struct = S.unknown + let schema = S.unknown - t->Assert.deepEqual("true"->S.parseJsonStringWith(struct), Ok(true->Obj.magic), ()) + t->Assert.deepEqual("true"->S.parseJsonStringWith(schema), Ok(true->Obj.magic), ()) }) test("Fails to parse JSON", t => { - let struct = S.bool + let schema = S.bool - switch "123,"->S.parseJsonStringWith(struct) { + switch "123,"->S.parseJsonStringWith(schema) { | Ok(_) => t->Assert.fail("Must return Error") | Error({code, operation, path}) => { t->Assert.deepEqual(operation, Parsing, ()) @@ -31,13 +31,13 @@ test("Fails to parse JSON", t => { }) test("Fails to parse", t => { - let struct = S.bool + let schema = S.bool t->Assert.deepEqual( - "123"->S.parseJsonStringWith(struct), + "123"->S.parseJsonStringWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: Obj.magic(123)}), + code: InvalidType({expected: schema->S.toUnknown, received: Obj.magic(123)}), operation: Parsing, path: S.Path.empty, }), diff --git a/packages/tests/src/core/S_parseWith_test.res b/packages/tests/src/core/S_parseWith_test.res index 6c502dde..32d260bd 100644 --- a/packages/tests/src/core/S_parseWith_test.res +++ b/packages/tests/src/core/S_parseWith_test.res @@ -2,25 +2,25 @@ open Ava open RescriptCore test("Successfully parses", t => { - let struct = S.bool + let schema = S.bool - t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseWith(struct), Ok(true), ()) + t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseWith(schema), Ok(true), ()) }) test("Successfully parses unknown", t => { - let struct = S.unknown + let schema = S.unknown - t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseWith(struct), Ok(true->Obj.magic), ()) + t->Assert.deepEqual(JSON.Encode.bool(true)->S.parseWith(schema), Ok(true->Obj.magic), ()) }) test("Fails to parse", t => { - let struct = S.bool + let schema = S.bool t->Assert.deepEqual( - %raw("123")->S.parseWith(struct), + %raw("123")->S.parseWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw("123")}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw("123")}), operation: Parsing, path: S.Path.empty, }), diff --git a/packages/tests/src/core/S_preprocess_test.res b/packages/tests/src/core/S_preprocess_test.res index c9d700a1..d723233d 100644 --- a/packages/tests/src/core/S_preprocess_test.res +++ b/packages/tests/src/core/S_preprocess_test.res @@ -23,38 +23,38 @@ let preprocessNumberToString = S.preprocess(_, _ => { }) test("Successfully parses", t => { - let struct = S.string->preprocessNumberToString + let schema = S.string->preprocessNumberToString - t->Assert.deepEqual(123->S.parseAnyWith(struct), Ok("123"), ()) - t->Assert.deepEqual("Hello world!"->S.parseAnyWith(struct), Ok("Hello world!"), ()) + t->Assert.deepEqual(123->S.parseAnyWith(schema), Ok("123"), ()) + t->Assert.deepEqual("Hello world!"->S.parseAnyWith(schema), Ok("Hello world!"), ()) }) test("Fails to parse when user raises error in parser", t => { - let struct = S.string->S.preprocess(s => {parser: _ => s.fail("User error")}) + let schema = S.string->S.preprocess(s => {parser: _ => s.fail("User error")}) t->Assert.deepEqual( - "Hello world!"->S.parseAnyWith(struct), + "Hello world!"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("User error"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully serializes", t => { - let struct = S.string->preprocessNumberToString + let schema = S.string->preprocessNumberToString t->Assert.deepEqual( - "Hello world!"->S.serializeToUnknownWith(struct), + "Hello world!"->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) - t->Assert.deepEqual("123"->S.serializeToUnknownWith(struct), Ok(%raw(`123`)), ()) + t->Assert.deepEqual("123"->S.serializeToUnknownWith(schema), Ok(%raw(`123`)), ()) }) test("Fails to serialize when user raises error in serializer", t => { - let struct = S.string->S.preprocess(s => {serializer: _ => s.fail("User error")}) + let schema = S.string->S.preprocess(s => {serializer: _ => s.fail("User error")}) t->Assert.deepEqual( - "Hello world!"->S.serializeToUnknownWith(struct), + "Hello world!"->S.serializeToUnknownWith(schema), Error( U.error({code: OperationFailed("User error"), operation: Serializing, path: S.Path.empty}), ), @@ -63,13 +63,13 @@ test("Fails to serialize when user raises error in serializer", t => { }) test("Preprocess operations applyed in the right order when parsing", t => { - let struct = + let schema = S.int ->S.preprocess(s => {parser: _ => s.fail("First preprocess")}) ->S.preprocess(s => {parser: _ => s.fail("Second preprocess")}) t->Assert.deepEqual( - 123->S.parseAnyWith(struct), + 123->S.parseAnyWith(schema), Error( U.error({code: OperationFailed("Second preprocess"), operation: Parsing, path: S.Path.empty}), ), @@ -78,13 +78,13 @@ test("Preprocess operations applyed in the right order when parsing", t => { }) test("Preprocess operations applyed in the right order when serializing", t => { - let struct = + let schema = S.int ->S.preprocess(s => {serializer: _ => s.fail("First preprocess")}) ->S.preprocess(s => {serializer: _ => s.fail("Second preprocess")}) t->Assert.deepEqual( - 123->S.serializeToUnknownWith(struct), + 123->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("First preprocess"), @@ -97,30 +97,30 @@ test("Preprocess operations applyed in the right order when serializing", t => { }) test("Fails to parse async using parseAnyWith", t => { - let struct = S.string->S.preprocess(_ => {asyncParser: value => () => Promise.resolve(value)}) + let schema = S.string->S.preprocess(_ => {asyncParser: value => () => Promise.resolve(value)}) t->Assert.deepEqual( - %raw(`"Hello world!"`)->S.parseAnyWith(struct), + %raw(`"Hello world!"`)->S.parseAnyWith(schema), Error(U.error({code: UnexpectedAsync, operation: Parsing, path: S.Path.empty})), (), ) }) asyncTest("Successfully parses async using parseAsyncWith", t => { - let struct = S.string->S.preprocess(_ => {asyncParser: value => () => Promise.resolve(value)}) + let schema = S.string->S.preprocess(_ => {asyncParser: value => () => Promise.resolve(value)}) %raw(`"Hello world!"`) - ->S.parseAsyncWith(struct) + ->S.parseAsyncWith(schema) ->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok("Hello world!"), ()) }) }) asyncTest("Fails to parse async with user error", t => { - let struct = S.string->S.preprocess(s => {asyncParser: _ => () => s.fail("User error")}) + let schema = S.string->S.preprocess(s => {asyncParser: _ => () => s.fail("User error")}) %raw(`"Hello world!"`) - ->S.parseAsyncWith(struct) + ->S.parseAsyncWith(schema) ->Promise.thenResolve(result => { t->Assert.deepEqual( result, @@ -137,38 +137,38 @@ asyncTest("Fails to parse async with user error", t => { }) test("Successfully parses with empty preprocess", t => { - let struct = S.string->S.preprocess(_ => {}) + let schema = S.string->S.preprocess(_ => {}) - t->Assert.deepEqual(%raw(`"Hello world!"`)->S.parseAnyWith(struct), Ok("Hello world!"), ()) + t->Assert.deepEqual(%raw(`"Hello world!"`)->S.parseAnyWith(schema), Ok("Hello world!"), ()) }) test("Successfully serializes with empty preprocess", t => { - let struct = S.string->S.preprocess(_ => {}) + let schema = S.string->S.preprocess(_ => {}) t->Assert.deepEqual( - "Hello world!"->S.serializeToUnknownWith(struct), + "Hello world!"->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) }) asyncTest("Can apply other actions after async preprocess", t => { - let struct = + let schema = S.string ->S.preprocess(_ => {asyncParser: value => () => Promise.resolve(value)}) ->S.String.trim ->S.preprocess(_ => {asyncParser: value => () => Promise.resolve(value)}) %raw(`" Hello world!"`) - ->S.parseAsyncWith(struct) + ->S.parseAsyncWith(schema) ->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok("Hello world!"), ()) }) }) -test("Applies preproces parser for union structs separately", t => { - let prepareEnvStruct = S.preprocess(_, s => { - switch s.struct->S.classify { +test("Applies preproces parser for union schemas separately", t => { + let prepareEnvSchema = S.preprocess(_, s => { + switch s.schema->S.classify { | Literal(Boolean(_)) | Bool => { parser: unknown => { @@ -198,23 +198,23 @@ test("Applies preproces parser for union structs separately", t => { } }) - let struct = + let schema = S.union([ S.bool->S.variant(bool => #Bool(bool)), S.int->S.variant(int => #Int(int)), - ])->prepareEnvStruct + ])->prepareEnvSchema - t->Assert.deepEqual("f"->S.parseAnyWith(struct), Ok(#Bool(false)), ()) - t->Assert.deepEqual("1"->S.parseAnyWith(struct), Ok(#Bool(true)), ()) - t->Assert.deepEqual("2"->S.parseAnyWith(struct), Ok(#Int(2)), ()) + t->Assert.deepEqual("f"->S.parseAnyWith(schema), Ok(#Bool(false)), ()) + t->Assert.deepEqual("1"->S.parseAnyWith(schema), Ok(#Bool(true)), ()) + t->Assert.deepEqual("2"->S.parseAnyWith(schema), Ok(#Int(2)), ()) }) -test("Applies preproces serializer for union structs separately", t => { - let struct = S.union([ +test("Applies preproces serializer for union schemas separately", t => { + let schema = S.union([ S.bool->S.variant(bool => #Bool(bool)), S.int->S.variant(int => #Int(int)), ])->S.preprocess(s => { - switch s.struct->S.classify { + switch s.schema->S.classify { | Bool => { serializer: unknown => { if unknown->Obj.magic === true { @@ -239,58 +239,58 @@ test("Applies preproces serializer for union structs separately", t => { } }) - t->Assert.deepEqual(#Bool(false)->S.serializeToUnknownWith(struct), Ok(%raw(`"0"`)), ()) - t->Assert.deepEqual(#Bool(true)->S.serializeToUnknownWith(struct), Ok(%raw(`"1"`)), ()) - t->Assert.deepEqual(#Int(2)->S.serializeToUnknownWith(struct), Ok(%raw(`"2"`)), ()) + t->Assert.deepEqual(#Bool(false)->S.serializeToUnknownWith(schema), Ok(%raw(`"0"`)), ()) + t->Assert.deepEqual(#Bool(true)->S.serializeToUnknownWith(schema), Ok(%raw(`"1"`)), ()) + t->Assert.deepEqual(#Int(2)->S.serializeToUnknownWith(schema), Ok(%raw(`"2"`)), ()) }) test("Doesn't fail to parse with preprocess when parser isn't provided", t => { - let struct = S.string->S.preprocess(_ => {serializer: value => value}) + let schema = S.string->S.preprocess(_ => {serializer: value => value}) - t->Assert.deepEqual("Hello world!"->S.parseAnyWith(struct), Ok("Hello world!"), ()) + t->Assert.deepEqual("Hello world!"->S.parseAnyWith(schema), Ok("Hello world!"), ()) }) test("Doesn't fail to serialize with preprocess when serializer isn't provided", t => { - let struct = S.string->S.preprocess(_ => {parser: value => value}) + let schema = S.string->S.preprocess(_ => {parser: value => value}) t->Assert.deepEqual( - "Hello world!"->S.serializeToUnknownWith(struct), + "Hello world!"->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) }) test("Compiled parse code snapshot", t => { - let struct = S.int->S.preprocess(_ => { + let schema = S.int->S.preprocess(_ => { parser: _ => 1->Int.toFloat, serializer: _ => 1.->Int.fromFloat, }) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;v0=e[0](i);if(typeof v0!=="number"||v0>2147483647||v0<-2147483648||v0%1!==0){e[1](v0)}return v0}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = S.int->S.preprocess(_ => { + let schema = S.int->S.preprocess(_ => { asyncParser: _ => () => 1->Int.toFloat->Promise.resolve, serializer: _ => 1.->Int.fromFloat, }) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1;v0=e[0](i);v1=()=>v0().then(v2=>{if(typeof v2!=="number"||v2>2147483647||v2<-2147483648||v2%1!==0){e[1](v2)}return v2});return v1}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.int->S.preprocess(_ => { + let schema = S.int->S.preprocess(_ => { parser: _ => 1->Int.toFloat, serializer: _ => 1.->Int.fromFloat, }) - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{return e[0](i)}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{return e[0](i)}`) }) diff --git a/packages/tests/src/core/S_recursive_test.res b/packages/tests/src/core/S_recursive_test.res index e83ac6da..58cac7dc 100644 --- a/packages/tests/src/core/S_recursive_test.res +++ b/packages/tests/src/core/S_recursive_test.res @@ -7,11 +7,11 @@ type rec node = { } test("Successfully parses recursive object", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field("Id", S.string), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }) @@ -23,7 +23,7 @@ test("Successfully parses recursive object", t => { {"Id": "2", "Children": []}, {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], - }->S.parseAnyWith(nodeStruct), + }->S.parseAnyWith(nodeSchema), Ok({ id: "1", children: [{id: "2", children: []}, {id: "3", children: [{id: "4", children: []}]}], @@ -33,11 +33,11 @@ test("Successfully parses recursive object", t => { }) asyncTest("Successfully parses recursive object using S.parseAsyncWith", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field("Id", S.string), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }) @@ -49,7 +49,7 @@ asyncTest("Successfully parses recursive object using S.parseAsyncWith", t => { {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], }`) - ->S.parseAsyncWith(nodeStruct) + ->S.parseAsyncWith(nodeSchema) ->Promise.thenResolve(result => { t->Assert.deepEqual( result, @@ -63,11 +63,11 @@ asyncTest("Successfully parses recursive object using S.parseAsyncWith", t => { }) test("Successfully serializes recursive object", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field("Id", S.string), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }) @@ -76,7 +76,7 @@ test("Successfully serializes recursive object", t => { { id: "1", children: [{id: "2", children: []}, {id: "3", children: [{id: "4", children: []}]}], - }->S.serializeToUnknownWith(nodeStruct), + }->S.serializeToUnknownWith(nodeSchema), Ok( %raw(`{ "Id": "1", @@ -91,7 +91,7 @@ test("Successfully serializes recursive object", t => { }) test("Fails to parse nested recursive object", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field( @@ -104,7 +104,7 @@ test("Fails to parse nested recursive object", t => { }, ), ), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }) @@ -116,7 +116,7 @@ test("Fails to parse nested recursive object", t => { {"Id": "2", "Children": []}, {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], - }->S.parseAnyWith(nodeStruct), + }->S.parseAnyWith(nodeSchema), Error( U.error({ code: OperationFailed("Invalid id"), @@ -129,11 +129,11 @@ test("Fails to parse nested recursive object", t => { }) test("Fails to parse nested recursive object inside of another object", t => { - let struct = S.object(s => + let schema = S.object(s => s.field( "recursive", S.recursive( - nodeStruct => { + nodeSchema => { S.object( s => { id: s.field( @@ -146,7 +146,7 @@ test("Fails to parse nested recursive object inside of another object", t => { }, ), ), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }, @@ -163,7 +163,7 @@ test("Fails to parse nested recursive object inside of another object", t => { {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], }, - }->S.parseAnyWith(struct), + }->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Invalid id"), @@ -176,7 +176,7 @@ test("Fails to parse nested recursive object inside of another object", t => { }) test("Fails to serialise nested recursive object", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field( @@ -189,7 +189,7 @@ test("Fails to serialise nested recursive object", t => { }, ), ), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }) @@ -198,7 +198,7 @@ test("Fails to serialise nested recursive object", t => { { id: "1", children: [{id: "2", children: []}, {id: "3", children: [{id: "4", children: []}]}], - }->S.serializeToUnknownWith(nodeStruct), + }->S.serializeToUnknownWith(nodeSchema), Error( U.error({ code: OperationFailed("Invalid id"), @@ -211,13 +211,13 @@ test("Fails to serialise nested recursive object", t => { }) test( - "Recursively transforms all objects when added transform to the recursive's function returned struct", + "Recursively transforms all objects when added transform to the recursive's function returned schema", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field("Id", S.string), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, )->S.transform( _ => { @@ -234,7 +234,7 @@ test( {"Id": "2", "Children": []}, {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], - }->S.parseAnyWith(nodeStruct), + }->S.parseAnyWith(nodeSchema), Ok({ id: "node_1", children: [ @@ -251,7 +251,7 @@ test( {id: "node_2", children: []}, {id: "node_3", children: [{id: "node_4", children: []}]}, ], - }->S.serializeToUnknownWith(nodeStruct), + }->S.serializeToUnknownWith(nodeSchema), Ok( { "Id": "1", @@ -266,15 +266,15 @@ test( }, ) -test("Recursively transforms nested objects when added transform to the placeholder struct", t => { - let nodeStruct = S.recursive(nodeStruct => { +test("Recursively transforms nested objects when added transform to the placeholder schema", t => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field("Id", S.string), children: s.field( "Children", S.array( - nodeStruct->S.transform( + nodeSchema->S.transform( _ => { parser: node => {...node, id: `child_${node.id}`}, serializer: node => {...node, id: node.id->String.sliceToEnd(~start=6)}, @@ -293,7 +293,7 @@ test("Recursively transforms nested objects when added transform to the placehol {"Id": "2", "Children": []}, {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], - }->S.parseAnyWith(nodeStruct), + }->S.parseAnyWith(nodeSchema), Ok({ id: "1", children: [ @@ -310,7 +310,7 @@ test("Recursively transforms nested objects when added transform to the placehol {id: "child_2", children: []}, {id: "child_3", children: [{id: "child_4", children: []}]}, ], - }->S.serializeToUnknownWith(nodeStruct), + }->S.serializeToUnknownWith(nodeSchema), Ok( { "Id": "1", @@ -325,11 +325,11 @@ test("Recursively transforms nested objects when added transform to the placehol }) test("Shallowly transforms object when added transform to the S.recursive result", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field("Id", S.string), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) })->S.transform(_ => { @@ -344,7 +344,7 @@ test("Shallowly transforms object when added transform to the S.recursive result {"Id": "2", "Children": []}, {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], - }->S.parseAnyWith(nodeStruct), + }->S.parseAnyWith(nodeSchema), Ok({ id: "parent_1", children: [{id: "2", children: []}, {id: "3", children: [{id: "4", children: []}]}], @@ -355,7 +355,7 @@ test("Shallowly transforms object when added transform to the S.recursive result { id: "parent_1", children: [{id: "2", children: []}, {id: "3", children: [{id: "4", children: []}]}], - }->S.serializeToUnknownWith(nodeStruct), + }->S.serializeToUnknownWith(nodeSchema), Ok( { "Id": "1", @@ -369,14 +369,14 @@ test("Shallowly transforms object when added transform to the S.recursive result ) }) -test("Creates struct without async parse function using S.recursive", t => { +test("Creates schema without async parse function using S.recursive", t => { t->Assert.notThrows(() => { S.recursive( - nodeStruct => { + nodeSchema => { S.object( s => { id: s.field("Id", S.string), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }, @@ -384,17 +384,17 @@ test("Creates struct without async parse function using S.recursive", t => { }, ()) }) -test("Creates struct with async parse function using S.recursive", t => { +test("Creates schema with async parse function using S.recursive", t => { t->Assert.notThrows(() => { S.recursive( - nodeStruct => { + nodeSchema => { S.object( s => { id: s.field( "Id", S.string->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)}), ), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }, @@ -403,11 +403,11 @@ test("Creates struct with async parse function using S.recursive", t => { }) asyncTest("Successfully parses recursive object with async parse function", t => { - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field("Id", S.string->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }) @@ -419,7 +419,7 @@ asyncTest("Successfully parses recursive object with async parse function", t => {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], }`) - ->S.parseAsyncWith(nodeStruct) + ->S.parseAsyncWith(nodeSchema) ->Promise.thenResolve(result => { t->Assert.deepEqual( result, @@ -436,7 +436,7 @@ test("Parses recursive object with async fields in parallel", t => { let unresolvedPromise = Promise.make((_, _) => ()) let actionCounter = ref(0) - let nodeStruct = S.recursive(nodeStruct => { + let nodeSchema = S.recursive(nodeSchema => { S.object( s => { id: s.field( @@ -450,7 +450,7 @@ test("Parses recursive object with async fields in parallel", t => { }, ), ), - children: s.field("Children", S.array(nodeStruct)), + children: s.field("Children", S.array(nodeSchema)), }, ) }) @@ -462,7 +462,7 @@ test("Parses recursive object with async fields in parallel", t => { {"Id": "3", "Children": [{"Id": "4", "Children": []}]}, ], }`) - ->S.parseAsyncWith(nodeStruct) + ->S.parseAsyncWith(nodeSchema) ->ignore t->Assert.deepEqual(actionCounter.contents, 4, ()) diff --git a/packages/tests/src/core/S_refine_test.res b/packages/tests/src/core/S_refine_test.res index b7b8db6c..fff4a62e 100644 --- a/packages/tests/src/core/S_refine_test.res +++ b/packages/tests/src/core/S_refine_test.res @@ -1,14 +1,14 @@ open Ava test("Successfully refines on parsing", t => { - let struct = S.int->S.refine(s => value => + let schema = S.int->S.refine(s => value => if value < 0 { s.fail("Should be positive") }) - t->Assert.deepEqual(%raw(`12`)->S.parseAnyWith(struct), Ok(12), ()) + t->Assert.deepEqual(%raw(`12`)->S.parseAnyWith(schema), Ok(12), ()) t->Assert.deepEqual( - %raw(`-12`)->S.parseAnyWith(struct), + %raw(`-12`)->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Should be positive"), @@ -21,13 +21,13 @@ test("Successfully refines on parsing", t => { }) test("Fails with custom path", t => { - let struct = S.int->S.refine(s => value => + let schema = S.int->S.refine(s => value => if value < 0 { s.fail(~path=S.Path.fromArray(["data", "myInt"]), "Should be positive") }) t->Assert.deepEqual( - %raw(`-12`)->S.parseAnyWith(struct), + %raw(`-12`)->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("Should be positive"), @@ -40,14 +40,14 @@ test("Fails with custom path", t => { }) test("Successfully refines on serializing", t => { - let struct = S.int->S.refine(s => value => + let schema = S.int->S.refine(s => value => if value < 0 { s.fail("Should be positive") }) - t->Assert.deepEqual(12->S.serializeToUnknownWith(struct), Ok(%raw("12")), ()) + t->Assert.deepEqual(12->S.serializeToUnknownWith(schema), Ok(%raw("12")), ()) t->Assert.deepEqual( - -12->S.serializeToUnknownWith(struct), + -12->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Should be positive"), @@ -60,7 +60,7 @@ test("Successfully refines on serializing", t => { }) test("Compiled parse code snapshot for simple object with refine", t => { - let struct = S.object(s => + let schema = S.object(s => { "foo": s.field("foo", S.string), "bar": s.field("bar", S.bool), @@ -68,7 +68,7 @@ test("Compiled parse code snapshot for simple object with refine", t => { )->S.refine(s => _ => s.fail("foo")) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1,v2;if(!i||i.constructor!==Object){e[3](i)}v0=i["foo"];if(typeof v0!=="string"){e[0](v0)}v1=i["bar"];if(typeof v1!=="boolean"){e[1](v1)}v2={"foo":v0,"bar":v1,};e[2](v2);return v2}`, ) diff --git a/packages/tests/src/core/S_serializeOrRaiseWith_test.res b/packages/tests/src/core/S_serializeOrRaiseWith_test.res index 4cd41950..f11ce309 100644 --- a/packages/tests/src/core/S_serializeOrRaiseWith_test.res +++ b/packages/tests/src/core/S_serializeOrRaiseWith_test.res @@ -1,16 +1,16 @@ open Ava test("Successfully serializes", t => { - let struct = S.bool + let schema = S.bool - t->Assert.deepEqual(true->S.serializeOrRaiseWith(struct), true->Obj.magic, ()) + t->Assert.deepEqual(true->S.serializeOrRaiseWith(schema), true->Obj.magic, ()) }) test("Fails to serialize", t => { - let struct = S.bool->S.refine(s => _ => s.fail("User error")) + let schema = S.bool->S.refine(s => _ => s.fail("User error")) let maybeError = try { - true->S.serializeOrRaiseWith(struct)->ignore + true->S.serializeOrRaiseWith(schema)->ignore None } catch { | S.Raised(error) => Some(error) diff --git a/packages/tests/src/core/S_serializeToJsonStringWith_test.res b/packages/tests/src/core/S_serializeToJsonStringWith_test.res index 73a856a7..0013ebd4 100644 --- a/packages/tests/src/core/S_serializeToJsonStringWith_test.res +++ b/packages/tests/src/core/S_serializeToJsonStringWith_test.res @@ -1,13 +1,13 @@ open Ava test("Successfully parses", t => { - let struct = S.bool + let schema = S.bool - t->Assert.deepEqual(true->S.serializeToJsonStringWith(struct), Ok("true"), ()) + t->Assert.deepEqual(true->S.serializeToJsonStringWith(schema), Ok("true"), ()) }) test("Successfully parses object", t => { - let struct = S.object(s => + let schema = S.object(s => { "id": s.field("id", S.string), "isDeleted": s.field("isDeleted", S.bool), @@ -18,14 +18,14 @@ test("Successfully parses object", t => { { "id": "0", "isDeleted": true, - }->S.serializeToJsonStringWith(struct), + }->S.serializeToJsonStringWith(schema), Ok(`{"id":"0","isDeleted":true}`), (), ) }) test("Successfully parses object with space", t => { - let struct = S.object(s => + let schema = S.object(s => { "id": s.field("id", S.string), "isDeleted": s.field("isDeleted", S.bool), @@ -36,7 +36,7 @@ test("Successfully parses object with space", t => { { "id": "0", "isDeleted": true, - }->S.serializeToJsonStringWith(~space=2, struct), + }->S.serializeToJsonStringWith(~space=2, schema), Ok(`{ "id": "0", "isDeleted": true @@ -45,11 +45,11 @@ test("Successfully parses object with space", t => { ) }) -test("Fails to serialize Unknown struct", t => { - let struct = S.unknown +test("Fails to serialize Unknown schema", t => { + let schema = S.unknown t->Assert.deepEqual( - Obj.magic(123)->S.serializeToJsonStringWith(struct), - Error(U.error({code: InvalidJsonStruct(struct), operation: Serializing, path: S.Path.empty})), + Obj.magic(123)->S.serializeToJsonStringWith(schema), + Error(U.error({code: InvalidJsonStruct(schema), operation: Serializing, path: S.Path.empty})), (), ) }) diff --git a/packages/tests/src/core/S_serializeWith_test.res b/packages/tests/src/core/S_serializeWith_test.res index 0467b4c0..9f2a7646 100644 --- a/packages/tests/src/core/S_serializeWith_test.res +++ b/packages/tests/src/core/S_serializeWith_test.res @@ -1,7 +1,7 @@ open Ava open RescriptCore -test("Successfully serializes jsonable structs", t => { +test("Successfully serializes jsonable schemas", t => { t->Assert.deepEqual(true->S.serializeWith(S.bool), true->JSON.Encode.bool->Ok, ()) t->Assert.deepEqual(true->S.serializeWith(S.literal(true)), true->JSON.Encode.bool->Ok, ()) t->Assert.deepEqual("abc"->S.serializeWith(S.string), "abc"->JSON.Encode.string->Ok, ()) @@ -69,13 +69,13 @@ test("Successfully serializes jsonable structs", t => { ) }) -test("Fails to serialize Option struct", t => { - let struct = S.option(S.bool) +test("Fails to serialize Option schema", t => { + let schema = S.option(S.bool) t->Assert.deepEqual( - None->S.serializeWith(struct), + None->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -85,12 +85,12 @@ test("Fails to serialize Option struct", t => { }) test("Fails to serialize Undefined literal", t => { - let struct = S.literal() + let schema = S.literal() t->Assert.deepEqual( - ()->S.serializeWith(struct), + ()->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -101,12 +101,12 @@ test("Fails to serialize Undefined literal", t => { test("Fails to serialize Function literal", t => { let fn = () => () - let struct = S.literal(fn) + let schema = S.literal(fn) t->Assert.deepEqual( - fn->S.serializeWith(struct), + fn->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -117,12 +117,12 @@ test("Fails to serialize Function literal", t => { test("Fails to serialize Object literal", t => { let error = %raw(`new Error("foo")`) - let struct = S.literal(error) + let schema = S.literal(error) t->Assert.deepEqual( - error->S.serializeWith(struct), + error->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -133,12 +133,12 @@ test("Fails to serialize Object literal", t => { test("Fails to serialize Symbol literal", t => { let symbol = %raw(`Symbol()`) - let struct = S.literal(symbol) + let schema = S.literal(symbol) t->Assert.deepEqual( - symbol->S.serializeWith(struct), + symbol->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -149,12 +149,12 @@ test("Fails to serialize Symbol literal", t => { test("Fails to serialize BigInt literal", t => { let bigint = %raw(`1234n`) - let struct = S.literal(bigint) + let schema = S.literal(bigint) t->Assert.deepEqual( - bigint->S.serializeWith(struct), + bigint->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -165,12 +165,12 @@ test("Fails to serialize BigInt literal", t => { test("Fails to serialize Dict literal with invalid field", t => { let dict = %raw(`{"foo": 123n}`) - let struct = S.literal(dict) + let schema = S.literal(dict) t->Assert.deepEqual( - dict->S.serializeWith(struct), + dict->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -180,12 +180,12 @@ test("Fails to serialize Dict literal with invalid field", t => { }) test("Fails to serialize NaN literal", t => { - let struct = S.literal(%raw(`NaN`)) + let schema = S.literal(%raw(`NaN`)) t->Assert.deepEqual( - ()->S.serializeWith(struct), + ()->S.serializeWith(schema), Error( U.error({ - code: InvalidJsonStruct(struct->S.toUnknown), + code: InvalidJsonStruct(schema->S.toUnknown), operation: Serializing, path: S.Path.empty, }), @@ -194,7 +194,7 @@ test("Fails to serialize NaN literal", t => { ) }) -test("Fails to serialize Unknown struct", t => { +test("Fails to serialize Unknown schema", t => { t->Assert.deepEqual( Obj.magic(123)->S.serializeWith(S.unknown), Error( @@ -204,7 +204,7 @@ test("Fails to serialize Unknown struct", t => { ) }) -test("Fails to serialize Never struct", t => { +test("Fails to serialize Never schema", t => { t->Assert.deepEqual( Obj.magic(123)->S.serializeWith(S.never), Error( @@ -218,7 +218,7 @@ test("Fails to serialize Never struct", t => { ) }) -test("Fails to serialize object with invalid nested struct", t => { +test("Fails to serialize object with invalid nested schema", t => { t->Assert.deepEqual( Obj.magic(true)->S.serializeWith(S.object(s => s.field("foo", S.unknown))), Error( @@ -232,7 +232,7 @@ test("Fails to serialize object with invalid nested struct", t => { ) }) -test("Fails to serialize tuple with invalid nested struct", t => { +test("Fails to serialize tuple with invalid nested schema", t => { t->Assert.deepEqual( Obj.magic(true)->S.serializeWith(S.tuple1(S.unknown)), Error( @@ -246,7 +246,7 @@ test("Fails to serialize tuple with invalid nested struct", t => { ) }) -test("Fails to serialize union if one of the items is an invalid struct", t => { +test("Fails to serialize union if one of the items is an invalid schema", t => { t->Assert.deepEqual( "foo"->S.serializeWith(S.union([S.string, S.unknown->(U.magic: S.t => S.t)])), Error( diff --git a/packages/tests/src/core/S_string_test.res b/packages/tests/src/core/S_string_test.res index d64dcf4c..55ddd5a3 100644 --- a/packages/tests/src/core/S_string_test.res +++ b/packages/tests/src/core/S_string_test.res @@ -7,19 +7,19 @@ module Common = { let factory = () => S.string test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidAny}), operation: Parsing, path: S.Path.empty, }), @@ -29,20 +29,20 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCode(~struct, ~op=#parse, `i=>{if(typeof i!=="string"){e[0](i)}return i}`) + t->U.assertCompiledCode(~schema, ~op=#parse, `i=>{if(typeof i!=="string"){e[0](i)}return i}`) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) } diff --git a/packages/tests/src/core/S_transform_test.res b/packages/tests/src/core/S_transform_test.res index d3aa0f03..363378d6 100644 --- a/packages/tests/src/core/S_transform_test.res +++ b/packages/tests/src/core/S_transform_test.res @@ -2,33 +2,33 @@ open Ava open RescriptCore test("Parses unknown primitive with transformation to the same type", t => { - let struct = S.string->S.transform(_ => {parser: value => value->String.trim}) + let schema = S.string->S.transform(_ => {parser: value => value->String.trim}) - t->Assert.deepEqual(" Hello world!"->S.parseAnyWith(struct), Ok("Hello world!"), ()) + t->Assert.deepEqual(" Hello world!"->S.parseAnyWith(schema), Ok("Hello world!"), ()) }) test("Parses unknown primitive with transformation to another type", t => { - let struct = S.int->S.transform(_ => {parser: value => value->Int.toFloat}) + let schema = S.int->S.transform(_ => {parser: value => value->Int.toFloat}) - t->Assert.deepEqual(123->S.parseAnyWith(struct), Ok(123.), ()) + t->Assert.deepEqual(123->S.parseAnyWith(schema), Ok(123.), ()) }) asyncTest( "Asynchronously parses unknown primitive with transformation to another type", async t => { - let struct = S.int->S.transform(_ => { + let schema = S.int->S.transform(_ => { asyncParser: value => () => Promise.resolve()->Promise.thenResolve(() => value->Int.toFloat), }) - t->Assert.deepEqual(await 123->S.parseAnyAsyncWith(struct), Ok(123.), ()) + t->Assert.deepEqual(await 123->S.parseAnyAsyncWith(schema), Ok(123.), ()) }, ) test("Fails to parse primitive with transform when parser isn't provided", t => { - let struct = S.string->S.transform(_ => {serializer: value => value}) + let schema = S.string->S.transform(_ => {serializer: value => value}) t->Assert.deepEqual( - "Hello world!"->S.parseAnyWith(struct), + "Hello world!"->S.parseAnyWith(schema), Error( U.error({ code: InvalidOperation({description: "The S.transform parser is missing"}), @@ -41,17 +41,17 @@ test("Fails to parse primitive with transform when parser isn't provided", t => }) test("Fails to parse when user raises error in a Transformed Primitive parser", t => { - let struct = S.string->S.transform(s => {parser: _ => s.fail("User error")}) + let schema = S.string->S.transform(s => {parser: _ => s.fail("User error")}) t->Assert.deepEqual( - "Hello world!"->S.parseAnyWith(struct), + "Hello world!"->S.parseAnyWith(schema), Error(U.error({code: OperationFailed("User error"), operation: Parsing, path: S.Path.empty})), (), ) }) test("Uses the path from failWithError called in the transform parser", t => { - let struct = S.array( + let schema = S.array( S.string->S.transform(s => { parser: _ => s.failWithError( @@ -65,7 +65,7 @@ test("Uses the path from failWithError called in the transform parser", t => { ) t->Assert.deepEqual( - ["Hello world!"]->S.parseAnyWith(struct), + ["Hello world!"]->S.parseAnyWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -78,7 +78,7 @@ test("Uses the path from failWithError called in the transform parser", t => { }) test("Uses the path from failWithError called in the transform serializer", t => { - let struct = S.array( + let schema = S.array( S.string->S.transform(s => { serializer: _ => s.failWithError( @@ -92,7 +92,7 @@ test("Uses the path from failWithError called in the transform serializer", t => ) t->Assert.deepEqual( - ["Hello world!"]->S.serializeWith(struct), + ["Hello world!"]->S.serializeWith(schema), Error( U.error({ code: OperationFailed("User error"), @@ -104,13 +104,13 @@ test("Uses the path from failWithError called in the transform serializer", t => ) }) -test("Transform parser passes through non rescript-struct errors", t => { - let struct = S.array( +test("Transform parser passes through non rescript-schema errors", t => { + let schema = S.array( S.string->S.transform(_ => {parser: _ => Exn.raiseError("Application crashed")}), ) t->Assert.throws( - () => {["Hello world!"]->S.parseAnyWith(struct)}, + () => {["Hello world!"]->S.parseAnyWith(schema)}, ~expectations={ message: "Application crashed", }, @@ -119,16 +119,16 @@ test("Transform parser passes through non rescript-struct errors", t => { }) test("Transform parser passes through other rescript exceptions", t => { - let struct = S.array(S.string->S.transform(_ => {parser: _ => U.raiseTestException()})) + let schema = S.array(S.string->S.transform(_ => {parser: _ => U.raiseTestException()})) - t->U.assertThrowsTestException(() => {["Hello world!"]->S.parseAnyWith(struct)}, ()) + t->U.assertThrowsTestException(() => {["Hello world!"]->S.parseAnyWith(schema)}, ()) }) -test("Transform definition passes through non rescript-struct errors", t => { - let struct = S.array(S.string->S.transform(_ => Exn.raiseError("Application crashed"))) +test("Transform definition passes through non rescript-schema errors", t => { + let schema = S.array(S.string->S.transform(_ => Exn.raiseError("Application crashed"))) t->Assert.throws( - () => {["Hello world!"]->S.parseAnyWith(struct)}, + () => {["Hello world!"]->S.parseAnyWith(schema)}, ~expectations={ message: "Application crashed", }, @@ -137,32 +137,32 @@ test("Transform definition passes through non rescript-struct errors", t => { }) test("Transform definition passes through other rescript exceptions", t => { - let struct = S.array(S.string->S.transform(_ => U.raiseTestException())) + let schema = S.array(S.string->S.transform(_ => U.raiseTestException())) - t->U.assertThrowsTestException(() => {["Hello world!"]->S.parseAnyWith(struct)}, ()) + t->U.assertThrowsTestException(() => {["Hello world!"]->S.parseAnyWith(schema)}, ()) }) test("Successfully serializes primitive with transformation to the same type", t => { - let struct = S.string->S.transform(_ => {serializer: value => value->String.trim}) + let schema = S.string->S.transform(_ => {serializer: value => value->String.trim}) t->Assert.deepEqual( - " Hello world!"->S.serializeToUnknownWith(struct), + " Hello world!"->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) }) test("Successfully serializes primitive with transformation to another type", t => { - let struct = S.float->S.transform(_ => {serializer: value => value->Int.toFloat}) + let schema = S.float->S.transform(_ => {serializer: value => value->Int.toFloat}) - t->Assert.deepEqual(123->S.serializeToUnknownWith(struct), Ok(%raw(`123`)), ()) + t->Assert.deepEqual(123->S.serializeToUnknownWith(schema), Ok(%raw(`123`)), ()) }) test("Transformed Primitive serializing fails when serializer isn't provided", t => { - let struct = S.string->S.transform(_ => {parser: value => value}) + let schema = S.string->S.transform(_ => {parser: value => value}) t->Assert.deepEqual( - "Hello world!"->S.serializeToUnknownWith(struct), + "Hello world!"->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({description: "The S.transform serializer is missing"}), @@ -175,10 +175,10 @@ test("Transformed Primitive serializing fails when serializer isn't provided", t }) test("Fails to serialize when user raises error in a Transformed Primitive serializer", t => { - let struct = S.string->S.transform(s => {serializer: _ => s.fail("User error")}) + let schema = S.string->S.transform(s => {serializer: _ => s.fail("User error")}) t->Assert.deepEqual( - "Hello world!"->S.serializeToUnknownWith(struct), + "Hello world!"->S.serializeToUnknownWith(schema), Error( U.error({code: OperationFailed("User error"), operation: Serializing, path: S.Path.empty}), ), @@ -187,13 +187,13 @@ test("Fails to serialize when user raises error in a Transformed Primitive seria }) test("Transform operations applyed in the right order when parsing", t => { - let struct = + let schema = S.int ->S.transform(s => {parser: _ => s.fail("First transform")}) ->S.transform(s => {parser: _ => s.fail("Second transform")}) t->Assert.deepEqual( - 123->S.parseAnyWith(struct), + 123->S.parseAnyWith(schema), Error( U.error({code: OperationFailed("First transform"), operation: Parsing, path: S.Path.empty}), ), @@ -202,13 +202,13 @@ test("Transform operations applyed in the right order when parsing", t => { }) test("Transform operations applyed in the right order when serializing", t => { - let struct = + let schema = S.int ->S.transform(s => {serializer: _ => s.fail("First transform")}) ->S.transform(s => {serializer: _ => s.fail("Second transform")}) t->Assert.deepEqual( - 123->S.serializeToUnknownWith(struct), + 123->S.serializeToUnknownWith(schema), Error( U.error({ code: OperationFailed("Second transform"), @@ -225,25 +225,25 @@ test( t => { let any = %raw(`123`) - let struct = S.int->S.transform(_ => { + let schema = S.int->S.transform(_ => { parser: int => int->Int.toFloat, serializer: value => value->Int.fromFloat, }) t->Assert.deepEqual( - any->S.parseAnyWith(struct)->Result.map(object => object->S.serializeToUnknownWith(struct)), + any->S.parseAnyWith(schema)->Result.map(object => object->S.serializeToUnknownWith(schema)), Ok(Ok(any)), (), ) }, ) -test("Fails to parse struct with transform having both parser and asyncParser", t => { - let struct = +test("Fails to parse schema with transform having both parser and asyncParser", t => { + let schema = S.string->S.transform(_ => {parser: _ => (), asyncParser: _ => () => Promise.resolve()}) t->Assert.deepEqual( - "foo"->S.parseAnyWith(struct), + "foo"->S.parseAnyWith(schema), Error( U.error({ code: InvalidOperation({ @@ -258,46 +258,46 @@ test("Fails to parse struct with transform having both parser and asyncParser", }) test("Fails to parse async using parseAnyWith", t => { - let struct = S.string->S.transform(_ => {asyncParser: value => () => Promise.resolve(value)}) + let schema = S.string->S.transform(_ => {asyncParser: value => () => Promise.resolve(value)}) t->Assert.deepEqual( - %raw(`"Hello world!"`)->S.parseAnyWith(struct), + %raw(`"Hello world!"`)->S.parseAnyWith(schema), Error(U.error({code: UnexpectedAsync, operation: Parsing, path: S.Path.empty})), (), ) }) test("Successfully parses with empty transform", t => { - let struct = S.string->S.transform(_ => {}) + let schema = S.string->S.transform(_ => {}) - t->Assert.deepEqual(%raw(`"Hello world!"`)->S.parseAnyWith(struct), Ok("Hello world!"), ()) + t->Assert.deepEqual(%raw(`"Hello world!"`)->S.parseAnyWith(schema), Ok("Hello world!"), ()) }) test("Successfully serializes with empty transform", t => { - let struct = S.string->S.transform(_ => {}) + let schema = S.string->S.transform(_ => {}) t->Assert.deepEqual( - "Hello world!"->S.serializeToUnknownWith(struct), + "Hello world!"->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) }) asyncTest("Successfully parses async using parseAsyncWith", t => { - let struct = S.string->S.transform(_ => {asyncParser: value => () => Promise.resolve(value)}) + let schema = S.string->S.transform(_ => {asyncParser: value => () => Promise.resolve(value)}) %raw(`"Hello world!"`) - ->S.parseAsyncWith(struct) + ->S.parseAsyncWith(schema) ->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok("Hello world!"), ()) }) }) asyncTest("Fails to parse async with user error", t => { - let struct = S.string->S.transform(s => {asyncParser: _ => () => s.fail("User error")}) + let schema = S.string->S.transform(s => {asyncParser: _ => () => s.fail("User error")}) %raw(`"Hello world!"`) - ->S.parseAsyncWith(struct) + ->S.parseAsyncWith(schema) ->Promise.thenResolve(result => { t->Assert.deepEqual( result, @@ -314,50 +314,50 @@ asyncTest("Fails to parse async with user error", t => { }) asyncTest("Can apply other actions after async transform", t => { - let struct = + let schema = S.string ->S.transform(_ => {asyncParser: value => () => Promise.resolve(value)}) ->S.String.trim ->S.transform(_ => {asyncParser: value => () => Promise.resolve(value)}) %raw(`" Hello world!"`) - ->S.parseAsyncWith(struct) + ->S.parseAsyncWith(schema) ->Promise.thenResolve(result => { t->Assert.deepEqual(result, Ok("Hello world!"), ()) }) }) test("Compiled parse code snapshot", t => { - let struct = S.int->S.transform(_ => { + let schema = S.int->S.transform(_ => { parser: int => int->Int.toFloat, serializer: value => value->Int.fromFloat, }) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{if(typeof i!=="number"||i>2147483647||i<-2147483648||i%1!==0){e[1](i)}return e[0](i)}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = S.int->S.transform(_ => { + let schema = S.int->S.transform(_ => { asyncParser: int => () => int->Int.toFloat->Promise.resolve, serializer: value => value->Int.fromFloat, }) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;if(typeof i!=="number"||i>2147483647||i<-2147483648||i%1!==0){e[1](i)}v0=e[0](i);return v0}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.int->S.transform(_ => { + let schema = S.int->S.transform(_ => { parser: int => int->Int.toFloat, serializer: value => value->Int.fromFloat, }) - t->U.assertCompiledCode(~struct, ~op=#serialize, `i=>{return e[0](i)}`) + t->U.assertCompiledCode(~schema, ~op=#serialize, `i=>{return e[0](i)}`) }) diff --git a/packages/tests/src/core/S_tuple1_test.res b/packages/tests/src/core/S_tuple1_test.res index edd57f91..8dbc6c58 100644 --- a/packages/tests/src/core/S_tuple1_test.res +++ b/packages/tests/src/core/S_tuple1_test.res @@ -8,16 +8,16 @@ module Common = { let factory = () => S.tuple1(S.int) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidTupleSize({ @@ -33,13 +33,13 @@ module Common = { }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidTypeAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidTypeAny}), operation: Parsing, path: S.Path.empty, }), @@ -49,8 +49,8 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) } diff --git a/packages/tests/src/core/S_tuple2_test.res b/packages/tests/src/core/S_tuple2_test.res index 4e78c745..ff4414d9 100644 --- a/packages/tests/src/core/S_tuple2_test.res +++ b/packages/tests/src/core/S_tuple2_test.res @@ -8,16 +8,16 @@ module Common = { let factory = () => S.tuple2(S.int, S.bool) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidTupleSize({ @@ -33,13 +33,13 @@ module Common = { }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidTypeAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidTypeAny}), operation: Parsing, path: S.Path.empty, }), @@ -49,8 +49,8 @@ module Common = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) } diff --git a/packages/tests/src/core/S_tuple_test.res b/packages/tests/src/core/S_tuple_test.res index 5221ae41..d6e31777 100644 --- a/packages/tests/src/core/S_tuple_test.res +++ b/packages/tests/src/core/S_tuple_test.res @@ -9,16 +9,16 @@ module Tuple0 = { let factory = () => S.tuple(_ => ()) test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(value), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(value), ()) }) test("Fails to parse invalid value", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidAny->S.parseAnyWith(struct), + invalidAny->S.parseAnyWith(schema), Error( U.error({ code: InvalidTupleSize({ @@ -34,13 +34,13 @@ module Tuple0 = { }) test("Fails to parse invalid type", t => { - let struct = factory() + let schema = factory() t->Assert.deepEqual( - invalidTypeAny->S.parseAnyWith(struct), + invalidTypeAny->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: invalidTypeAny}), + code: InvalidType({expected: schema->S.toUnknown, received: invalidTypeAny}), operation: Parsing, path: S.Path.empty, }), @@ -50,33 +50,33 @@ module Tuple0 = { }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(value->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(value->S.serializeToUnknownWith(schema), Ok(any), ()) }) } test("Classify of tuple with holes", t => { - let struct = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) + let schema = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) t->Assert.deepEqual( - struct->S.classify, + schema->S.classify, Tuple([S.string->S.toUnknown, S.unit->S.toUnknown, S.int->S.toUnknown]), (), ) }) test("Successfully parses tuple with holes", t => { - let struct = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) + let schema = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) - t->Assert.deepEqual(%raw(`["value",, 123]`)->S.parseAnyWith(struct), Ok("value", 123), ()) + t->Assert.deepEqual(%raw(`["value",, 123]`)->S.parseAnyWith(schema), Ok("value", 123), ()) }) test("Fails to parse tuple with holes", t => { - let struct = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) + let schema = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) t->Assert.deepEqual( - %raw(`["value", "smth", 123]`)->S.parseAnyWith(struct), + %raw(`["value", "smth", 123]`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: Undefined, received: %raw(`"smth"`)}), @@ -89,17 +89,17 @@ test("Fails to parse tuple with holes", t => { }) test("Successfully serializes tuple with holes", t => { - let struct = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) + let schema = S.tuple(s => (s.item(0, S.string), s.item(2, S.int))) t->Assert.deepEqual( - ("value", 123)->S.serializeToUnknownWith(struct), + ("value", 123)->S.serializeToUnknownWith(schema), Ok(%raw(`["value",, 123]`)), (), ) }) -test("Fails to serialize tuple struct with single item registered multiple times", t => { - let struct = S.tuple(s => { +test("Fails to serialize tuple schema with single item registered multiple times", t => { + let schema = S.tuple(s => { let item = s.item(0, S.string) { "item1": item, @@ -107,7 +107,7 @@ test("Fails to serialize tuple struct with single item registered multiple times } }) t->Assert.deepEqual( - {"item1": "foo", "item2": "foo"}->S.serializeToUnknownWith(struct), + {"item1": "foo", "item2": "foo"}->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({ @@ -122,13 +122,13 @@ test("Fails to serialize tuple struct with single item registered multiple times }) test(`Fails to serialize tuple with discriminant "Never"`, t => { - let struct = S.tuple(s => { + let schema = S.tuple(s => { ignore(s.item(0, S.never)) s.item(1, S.string) }) t->Assert.deepEqual( - "bar"->S.serializeToUnknownWith(struct), + "bar"->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({ @@ -143,22 +143,22 @@ test(`Fails to serialize tuple with discriminant "Never"`, t => { }) test("Successfully parses tuple transformed to variant", t => { - let struct = S.tuple(s => #VARIANT(s.item(0, S.bool))) + let schema = S.tuple(s => #VARIANT(s.item(0, S.bool))) - t->Assert.deepEqual(%raw(`[true]`)->S.parseAnyWith(struct), Ok(#VARIANT(true)), ()) + t->Assert.deepEqual(%raw(`[true]`)->S.parseAnyWith(schema), Ok(#VARIANT(true)), ()) }) test("Successfully serializes tuple transformed to variant", t => { - let struct = S.tuple(s => #VARIANT(s.item(0, S.bool))) + let schema = S.tuple(s => #VARIANT(s.item(0, S.bool))) - t->Assert.deepEqual(#VARIANT(true)->S.serializeToUnknownWith(struct), Ok(%raw(`[true]`)), ()) + t->Assert.deepEqual(#VARIANT(true)->S.serializeToUnknownWith(schema), Ok(%raw(`[true]`)), ()) }) test("Fails to serialize tuple transformed to variant", t => { - let struct = S.tuple(s => Ok(s.item(0, S.bool))) + let schema = S.tuple(s => Ok(s.item(0, S.bool))) t->Assert.deepEqual( - Error("foo")->S.serializeToUnknownWith(struct), + Error("foo")->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: String("Ok"), received: %raw(`"Error"`)}), @@ -170,7 +170,7 @@ test("Fails to serialize tuple transformed to variant", t => { ) }) -test("Fails to create tuple struct with single item defined multiple times", t => { +test("Fails to create tuple schema with single item defined multiple times", t => { t->Assert.throws( () => { S.tuple( @@ -182,14 +182,14 @@ test("Fails to create tuple struct with single item defined multiple times", t = ) }, ~expectations={ - message: `[rescript-struct] The item "0" is defined multiple times. If you want to duplicate the item, use S.transform instead.`, + message: `[rescript-schema] The item "0" is defined multiple times. If you want to duplicate the item, use S.transform instead.`, }, (), ) }) -test("Tuple struct parsing checks order", t => { - let struct = S.tuple(s => { +test("Tuple schema parsing checks order", t => { + let schema = S.tuple(s => { s.tag(1, "value") { "key": s.item(0, S.literal("value")), @@ -198,10 +198,10 @@ test("Tuple struct parsing checks order", t => { // Type check should be the first t->Assert.deepEqual( - %raw(`"foo"`)->S.parseAnyWith(struct), + %raw(`"foo"`)->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({expected: struct->S.toUnknown, received: %raw(`"foo"`)}), + code: InvalidType({expected: schema->S.toUnknown, received: %raw(`"foo"`)}), operation: Parsing, path: S.Path.empty, }), @@ -210,7 +210,7 @@ test("Tuple struct parsing checks order", t => { ) // Length check should be the second t->Assert.deepEqual( - %raw(`["wrong", "wrong", "value", "value"]`)->S.parseAnyWith(struct), + %raw(`["wrong", "wrong", "value", "value"]`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidTupleSize({expected: 2, received: 4}), @@ -222,7 +222,7 @@ test("Tuple struct parsing checks order", t => { ) // Tag check should be the third t->Assert.deepEqual( - %raw(`["wrong", "wrong"]`)->S.parseAnyWith(struct), + %raw(`["wrong", "wrong"]`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: String("value"), received: %raw(`"wrong"`)}), @@ -234,7 +234,7 @@ test("Tuple struct parsing checks order", t => { ) // Field check should be the last t->Assert.deepEqual( - %raw(`["wrong", "value"]`)->S.parseAnyWith(struct), + %raw(`["wrong", "value"]`)->S.parseAnyWith(schema), Error( U.error({ code: InvalidLiteral({expected: String("value"), received: %raw(`"wrong"`)}), @@ -246,7 +246,7 @@ test("Tuple struct parsing checks order", t => { ) // Parses valid t->Assert.deepEqual( - %raw(`["value", "value"]`)->S.parseAnyWith(struct), + %raw(`["value", "value"]`)->S.parseAnyWith(schema), Ok({ "key": "value", }), @@ -256,34 +256,34 @@ test("Tuple struct parsing checks order", t => { module Compiled = { test("Compiled parse code snapshot for simple tuple", t => { - let struct = S.tuple(s => (s.item(0, S.string), s.item(1, S.bool))) + let schema = S.tuple(s => (s.item(0, S.string), s.item(1, S.bool))) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1;if(!Array.isArray(i)){e[3](i)}if(i.length!==2){e[0](i.length)}v0=i["0"];if(typeof v0!=="string"){e[1](v0)}v1=i["1"];if(typeof v1!=="boolean"){e[2](v1)}return [v0,v1,]}`, ) }) test("Compiled parse code snapshot for simple tuple with async", t => { - let struct = S.tuple(s => ( + let schema = S.tuple(s => ( s.item(0, S.unknown->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)})), s.item(1, S.bool), )) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1,v2;if(!Array.isArray(i)){e[3](i)}if(i.length!==2){e[0](i.length)}v0=e[1](i["0"]);v1=i["1"];if(typeof v1!=="boolean"){e[2](v1)}v2=()=>Promise.all([v0()]).then(([v0])=>([v0,v1,]));return v2}`, ) }) test("Compiled serialize code snapshot for simple tuple", t => { - let struct = S.tuple(s => (s.item(0, S.string), s.item(1, S.bool))) + let schema = S.tuple(s => (s.item(0, S.string), s.item(1, S.bool))) // TODO: Improve (the output of tuple can be inlined) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;v0=[];v0["0"]=i["0"];v0["1"]=i["1"];return v0}`, ) @@ -292,7 +292,7 @@ module Compiled = { test( "Compiled parse code snapshot for simple tuple with transformation, constants and discriminants", t => { - let struct = S.tuple(s => { + let schema = S.tuple(s => { s.tag(0, 0) { "foo": s.item(1, S.string), @@ -302,7 +302,7 @@ module Compiled = { }) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1,v2;if(!Array.isArray(i)){e[6](i)}if(i.length!==3){e[0](i.length)}v2=i["0"];v2===e[4]||e[5](v2);v0=i["1"];if(typeof v0!=="string"){e[1](v0)}v1=i["2"];if(typeof v1!=="boolean"){e[2](v1)}return {"foo":v0,"bar":v1,"zoo":e[3],}}`, ) @@ -312,7 +312,7 @@ module Compiled = { test( "Compiled serialize code snapshot for simple tuple with transformation, constants and discriminants", t => { - let struct = S.tuple(s => { + let schema = S.tuple(s => { s.tag(0, 0) { "foo": s.item(1, S.string), @@ -322,7 +322,7 @@ module Compiled = { }) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;v0=[];if(i["zoo"]!==e[0]){e[1](i["zoo"])}v0["1"]=i["foo"];v0["2"]=i["bar"];v0["0"]=e[2];return v0}`, ) @@ -330,18 +330,18 @@ module Compiled = { ) } -test("Works with tuple struct used multiple times as a child struct", t => { - let appVersionSpecStruct = S.tuple(s => +test("Works with tuple schema used multiple times as a child schema", t => { + let appVersionSpecSchema = S.tuple(s => { "current": s.item(0, S.string), "minimum": s.item(1, S.string), } ) - let appVersionsStruct = S.object(s => + let appVersionsSchema = S.object(s => { - "ios": s.field("ios", appVersionSpecStruct), - "android": s.field("android", appVersionSpecStruct), + "ios": s.field("ios", appVersionSpecSchema), + "android": s.field("android", appVersionSpecSchema), } ) @@ -354,9 +354,9 @@ test("Works with tuple struct used multiple times as a child struct", t => { "android": {"current": "1.2", "minimum": "1.1"}, } - let value = rawAppVersions->S.parseAnyOrRaiseWith(appVersionsStruct) + let value = rawAppVersions->S.parseAnyOrRaiseWith(appVersionsSchema) t->Assert.deepEqual(value, appVersions, ()) - let data = appVersions->S.serializeOrRaiseWith(appVersionsStruct) + let data = appVersions->S.serializeOrRaiseWith(appVersionsSchema) t->Assert.deepEqual(data, rawAppVersions->Obj.magic, ()) }) diff --git a/packages/tests/src/core/S_union_test.res b/packages/tests/src/core/S_union_test.res index fda9933a..c72644db 100644 --- a/packages/tests/src/core/S_union_test.res +++ b/packages/tests/src/core/S_union_test.res @@ -1,40 +1,40 @@ open Ava open RescriptCore -test("Throws for a Union struct factory without structs", t => { +test("Throws for a Union schema factory without schemas", t => { t->Assert.throws( () => { S.union([]) }, ~expectations={ - message: "[rescript-struct] A Union struct factory require at least two structs.", + message: "[rescript-schema] A Union schema factory require at least two schemas.", }, (), ) }) -test("Throws for a Union struct factory with single struct", t => { +test("Throws for a Union schema factory with single schema", t => { t->Assert.throws( () => { S.union([S.string]) }, ~expectations={ - message: "[rescript-struct] A Union struct factory require at least two structs.", + message: "[rescript-schema] A Union schema factory require at least two schemas.", }, (), ) }) -test("Successfully creates a Union struct factory with two structs", t => { +test("Successfully creates a Union schema factory with two schemas", t => { t->Assert.notThrows(() => { S.union([S.string, S.string])->ignore }, ()) }) test("Successfully parses polymorphic variants", t => { - let struct = S.union([S.literal(#apple), S.literal(#orange)]) + let schema = S.union([S.literal(#apple), S.literal(#orange)]) - t->Assert.deepEqual(%raw(`"apple"`)->S.parseAnyWith(struct), Ok(#apple), ()) + t->Assert.deepEqual(%raw(`"apple"`)->S.parseAnyWith(schema), Ok(#apple), ()) }) module Advanced = { @@ -46,19 +46,19 @@ module Advanced = { type shape = Circle({radius: float}) | Square({x: float}) | Triangle({x: float, y: float}) - let circleStruct = S.object(s => { + let circleSchema = S.object(s => { s.tag("kind", "circle") Circle({ radius: s.field("radius", S.float), }) }) - let squareStruct = S.object(s => { + let squareSchema = S.object(s => { s.tag("kind", "square") Square({ x: s.field("x", S.float), }) }) - let triangleStruct = S.object(s => { + let triangleSchema = S.object(s => { s.tag("kind", "triangle") Triangle({ x: s.field("x", S.float), @@ -66,14 +66,14 @@ module Advanced = { }) }) - let shapeStruct = S.union([circleStruct, squareStruct, triangleStruct]) + let shapeSchema = S.union([circleSchema, squareSchema, triangleSchema]) test("Successfully parses Circle shape", t => { t->Assert.deepEqual( %raw(`{ "kind": "circle", "radius": 1, - }`)->S.parseAnyWith(shapeStruct), + }`)->S.parseAnyWith(shapeSchema), Ok(Circle({radius: 1.})), (), ) @@ -84,7 +84,7 @@ module Advanced = { %raw(`{ "kind": "square", "x": 2, - }`)->S.parseAnyWith(shapeStruct), + }`)->S.parseAnyWith(shapeSchema), Ok(Square({x: 2.})), (), ) @@ -96,7 +96,7 @@ module Advanced = { "kind": "triangle", "x": 2, "y": 3, - }`)->S.parseAnyWith(shapeStruct), + }`)->S.parseAnyWith(shapeSchema), Ok(Triangle({x: 2., y: 3.})), (), ) @@ -108,7 +108,7 @@ module Advanced = { "kind": "oval", "x": 2, "y": 3, - }`)->S.parseAnyWith(shapeStruct), + }`)->S.parseAnyWith(shapeSchema), Error( U.error({ code: InvalidUnion([ @@ -144,7 +144,7 @@ module Advanced = { "x": 2, "y": 3, } - }`)->S.parseAnyWith(S.object(s => s.field("field", shapeStruct))), + }`)->S.parseAnyWith(S.object(s => s.field("field", shapeSchema))), Error( U.error({ code: InvalidUnion([ @@ -174,13 +174,13 @@ module Advanced = { test("Fails to parse with invalid data type", t => { t->Assert.deepEqual( - %raw(`"Hello world!"`)->S.parseAnyWith(shapeStruct), + %raw(`"Hello world!"`)->S.parseAnyWith(shapeSchema), Error( U.error({ code: InvalidUnion([ U.error({ code: InvalidType({ - expected: circleStruct->S.toUnknown, + expected: circleSchema->S.toUnknown, received: %raw(`"Hello world!"`), }), operation: Parsing, @@ -188,7 +188,7 @@ module Advanced = { }), U.error({ code: InvalidType({ - expected: squareStruct->S.toUnknown, + expected: squareSchema->S.toUnknown, received: %raw(`"Hello world!"`), }), operation: Parsing, @@ -196,7 +196,7 @@ module Advanced = { }), U.error({ code: InvalidType({ - expected: triangleStruct->S.toUnknown, + expected: triangleSchema->S.toUnknown, received: %raw(`"Hello world!"`), }), operation: Parsing, @@ -211,8 +211,8 @@ module Advanced = { ) }) - test("Fails to serialize incomplete struct", t => { - let incompleteStruct = S.union([ + test("Fails to serialize incomplete schema", t => { + let incompleteSchema = S.union([ S.object(s => { s.tag("kind", "circle") Circle({ @@ -228,7 +228,7 @@ module Advanced = { ]) t->Assert.deepEqual( - Triangle({x: 2., y: 3.})->S.serializeToUnknownWith(incompleteStruct), + Triangle({x: 2., y: 3.})->S.serializeToUnknownWith(incompleteSchema), Error( U.error({ code: InvalidUnion([ @@ -253,7 +253,7 @@ module Advanced = { test("Successfully serializes Circle shape", t => { t->Assert.deepEqual( - Circle({radius: 1.})->S.serializeToUnknownWith(shapeStruct), + Circle({radius: 1.})->S.serializeToUnknownWith(shapeSchema), Ok( %raw(`{ "kind": "circle", @@ -266,7 +266,7 @@ module Advanced = { test("Successfully serializes Square shape", t => { t->Assert.deepEqual( - Square({x: 2.})->S.serializeToUnknownWith(shapeStruct), + Square({x: 2.})->S.serializeToUnknownWith(shapeSchema), Ok( %raw(`{ "kind": "square", @@ -279,7 +279,7 @@ module Advanced = { test("Successfully serializes Triangle shape", t => { t->Assert.deepEqual( - Triangle({x: 2., y: 3.})->S.serializeToUnknownWith(shapeStruct), + Triangle({x: 2., y: 3.})->S.serializeToUnknownWith(shapeSchema), Ok( %raw(`{ "kind": "triangle", @@ -295,7 +295,7 @@ module Advanced = { @unboxed type uboxedVariant = String(string) | Int(int) test("Successfully serializes unboxed variant", t => { - let struct = S.union([ + let schema = S.union([ S.string->S.variant(s => String(s)), S.string ->S.transform(_ => { @@ -305,46 +305,46 @@ test("Successfully serializes unboxed variant", t => { ->S.variant(i => Int(i)), ]) - t->Assert.deepEqual(String("abc")->S.serializeToUnknownWith(struct), Ok(%raw(`"abc"`)), ()) - t->Assert.deepEqual(Int(123)->S.serializeToUnknownWith(struct), Ok(%raw(`"123"`)), ()) + t->Assert.deepEqual(String("abc")->S.serializeToUnknownWith(schema), Ok(%raw(`"abc"`)), ()) + t->Assert.deepEqual(Int(123)->S.serializeToUnknownWith(schema), Ok(%raw(`"123"`)), ()) }) test("Compiled parse code snapshot", t => { - let struct = S.union([S.literal(0), S.literal(1)]) + let schema = S.union([S.literal(0), S.literal(1)]) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0;try{i===e[0]||e[1](i);v0=i}catch(v1){if(v1&&v1.s===s){try{i===e[2]||e[3](i);v0=i}catch(v2){if(v2&&v2.s===s){e[4]([v1,v2])}else{throw v2}}}else{throw v1}}return v0}`, ) }) test("Compiled async parse code snapshot", t => { - let struct = S.union([ + let schema = S.union([ S.literal(0)->S.transform(_ => {asyncParser: i => () => Promise.resolve(i)}), S.literal(1), ]) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{let v0,v1;try{i===e[0]||e[1](i);v0=e[2](i);throw v0}catch(v2){if(v2&&v2.s===s||v2===v0){try{i===e[3]||e[4](i);v1=()=>Promise.resolve(i)}catch(v3){if(v3&&v3.s===s){v1=()=>Promise.any([v2===v0?v2():Promise.reject(v2),Promise.reject(v3)]).catch(t=>{e[5](t.errors)})}else{throw v3}}}else{throw v2}}return v1}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.union([S.literal(0), S.literal(1)]) + let schema = S.union([S.literal(0), S.literal(1)]) // TODO: Improve compiled code t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;try{i===e[0]||e[1](i);v0=i}catch(v1){if(v1&&v1.s===s){try{i===e[2]||e[3](i);v0=i}catch(v2){if(v2&&v2.s===s){e[4]([v1,v2,])}else{throw v2}}}else{throw v1}}return v0}`, ) }) test("Compiled serialize code snapshot for unboxed variant", t => { - let struct = S.union([ + let schema = S.union([ S.string->S.variant(s => String(s)), S.string ->S.transform(_ => { @@ -355,7 +355,7 @@ test("Compiled serialize code snapshot for unboxed variant", t => { ]) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;try{if(typeof i!=="string"){e[0](i)}v0=i}catch(v1){if(v1&&v1.s===s){try{let v3;v3=e[1](i);if(typeof v3!=="string"){e[2](v3)}v0=v3}catch(v2){if(v2&&v2.s===s){e[3]([v1,v2,])}else{throw v2}}}else{throw v1}}return v0}`, ) diff --git a/packages/tests/src/core/S_unknown_test.res b/packages/tests/src/core/S_unknown_test.res index ffa2e22b..030c3de9 100644 --- a/packages/tests/src/core/S_unknown_test.res +++ b/packages/tests/src/core/S_unknown_test.res @@ -5,34 +5,34 @@ module Common = { let factory = () => S.unknown test("Successfully parses", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.parseAnyWith(struct), Ok(any), ()) + t->Assert.deepEqual(any->S.parseAnyWith(schema), Ok(any), ()) }) test("Successfully serializes", t => { - let struct = factory() + let schema = factory() - t->Assert.deepEqual(any->S.serializeToUnknownWith(struct), Ok(any), ()) + t->Assert.deepEqual(any->S.serializeToUnknownWith(schema), Ok(any), ()) }) test("Compiled parse code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCodeIsNoop(~struct, ~op=#parse) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#parse) }) test("Compiled serialize code snapshot", t => { - let struct = factory() + let schema = factory() - t->U.assertCompiledCodeIsNoop(~struct, ~op=#serialize) + t->U.assertCompiledCodeIsNoop(~schema, ~op=#serialize) }) } test("Doesn't return refinements", t => { - let struct = S.unknown - t->Assert.deepEqual(struct->S.String.refinements, [], ()) - t->Assert.deepEqual(struct->S.Array.refinements, [], ()) - t->Assert.deepEqual(struct->S.Int.refinements, [], ()) - t->Assert.deepEqual(struct->S.Float.refinements, [], ()) + let schema = S.unknown + t->Assert.deepEqual(schema->S.String.refinements, [], ()) + t->Assert.deepEqual(schema->S.Array.refinements, [], ()) + t->Assert.deepEqual(schema->S.Int.refinements, [], ()) + t->Assert.deepEqual(schema->S.Float.refinements, [], ()) }) diff --git a/packages/tests/src/core/S_variant_test.res b/packages/tests/src/core/S_variant_test.res index f06afa9c..33ba6121 100644 --- a/packages/tests/src/core/S_variant_test.res +++ b/packages/tests/src/core/S_variant_test.res @@ -1,19 +1,19 @@ open Ava test("Parses with wrapping the value in variant", t => { - let struct = S.string->S.variant(s => Ok(s)) + let schema = S.string->S.variant(s => Ok(s)) - t->Assert.deepEqual("Hello world!"->S.parseAnyWith(struct), Ok(Ok("Hello world!")), ()) + t->Assert.deepEqual("Hello world!"->S.parseAnyWith(schema), Ok(Ok("Hello world!")), ()) }) -test("Fails to parse wrapped struct", t => { - let struct = S.string->S.variant(s => Ok(s)) +test("Fails to parse wrapped schema", t => { + let schema = S.string->S.variant(s => Ok(s)) t->Assert.deepEqual( - 123->S.parseAnyWith(struct), + 123->S.parseAnyWith(schema), Error( U.error({ - code: InvalidType({received: 123->Obj.magic, expected: struct->S.toUnknown}), + code: InvalidType({received: 123->Obj.magic, expected: schema->S.toUnknown}), operation: Parsing, path: S.Path.empty, }), @@ -23,20 +23,20 @@ test("Fails to parse wrapped struct", t => { }) test("Serializes with unwrapping the value from variant", t => { - let struct = S.string->S.variant(s => Ok(s)) + let schema = S.string->S.variant(s => Ok(s)) t->Assert.deepEqual( - Ok("Hello world!")->S.serializeToUnknownWith(struct), + Ok("Hello world!")->S.serializeToUnknownWith(schema), Ok(%raw(`"Hello world!"`)), (), ) }) test("Fails to serialize when can't unwrap the value from variant", t => { - let struct = S.string->S.variant(s => Ok(s)) + let schema = S.string->S.variant(s => Ok(s)) t->Assert.deepEqual( - Error("Hello world!")->S.serializeToUnknownWith(struct), + Error("Hello world!")->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidLiteral({expected: String("Ok"), received: "Error"->Obj.magic}), @@ -49,16 +49,16 @@ test("Fails to serialize when can't unwrap the value from variant", t => { }) test("Successfully parses when the value is not used as the variant payload", t => { - let struct = S.string->S.variant(_ => #foo) + let schema = S.string->S.variant(_ => #foo) - t->Assert.deepEqual("Hello world!"->S.parseAnyWith(struct), Ok(#foo), ()) + t->Assert.deepEqual("Hello world!"->S.parseAnyWith(schema), Ok(#foo), ()) }) test("Fails to serialize when the value is not used as the variant payload", t => { - let struct = S.string->S.variant(_ => #foo) + let schema = S.string->S.variant(_ => #foo) t->Assert.deepEqual( - #foo->S.serializeToUnknownWith(struct), + #foo->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({ @@ -73,38 +73,38 @@ test("Fails to serialize when the value is not used as the variant payload", t = }) test( - "Successfully serializes when the value is not used as the variant payload for literal structs", + "Successfully serializes when the value is not used as the variant payload for literal schemas", t => { - let struct = S.tuple2(S.literal(true), S.literal(12))->S.variant(_ => #foo) + let schema = S.tuple2(S.literal(true), S.literal(12))->S.variant(_ => #foo) - t->Assert.deepEqual(#foo->S.serializeToUnknownWith(struct), Ok(%raw(`[true, 12]`)), ()) + t->Assert.deepEqual(#foo->S.serializeToUnknownWith(schema), Ok(%raw(`[true, 12]`)), ()) }, ) test("Successfully parses when tuple is destructured", t => { - let struct = S.tuple2(S.literal(true), S.literal(12))->S.variant(((_, twelve)) => twelve) + let schema = S.tuple2(S.literal(true), S.literal(12))->S.variant(((_, twelve)) => twelve) - t->Assert.deepEqual(%raw(`[true, 12]`)->S.parseAnyWith(struct), Ok(12), ()) + t->Assert.deepEqual(%raw(`[true, 12]`)->S.parseAnyWith(schema), Ok(12), ()) }) // TODO: Throw in proxy (???) // test("Fails to serialize when tuple is destructured", t => { -// let struct = S.tuple2(S.literal(true), S.literal(12))->S.variant(((_, twelve)) => twelve) +// let schema = S.tuple2(S.literal(true), S.literal(12))->S.variant(((_, twelve)) => twelve) -// t->Assert.deepEqual(12->S.serializeToUnknownWith(struct), Ok(%raw(`[true, 12]`)), ()) +// t->Assert.deepEqual(12->S.serializeToUnknownWith(schema), Ok(%raw(`[true, 12]`)), ()) // }) test("Successfully parses when value registered multiple times", t => { - let struct = S.string->S.variant(s => #Foo(s, s)) + let schema = S.string->S.variant(s => #Foo(s, s)) - t->Assert.deepEqual(%raw(`"abc"`)->S.parseAnyWith(struct), Ok(#Foo("abc", "abc")), ()) + t->Assert.deepEqual(%raw(`"abc"`)->S.parseAnyWith(schema), Ok(#Foo("abc", "abc")), ()) }) test("Fails to serialize when value registered multiple times", t => { - let struct = S.string->S.variant(s => #Foo(s, s)) + let schema = S.string->S.variant(s => #Foo(s, s)) t->Assert.deepEqual( - #Foo("abc", "abc")->S.serializeToUnknownWith(struct), + #Foo("abc", "abc")->S.serializeToUnknownWith(schema), Error( U.error({ code: InvalidOperation({ @@ -119,32 +119,32 @@ test("Fails to serialize when value registered multiple times", t => { }) test("Compiled parse code snapshot", t => { - let struct = S.string->S.variant(s => Ok(s)) + let schema = S.string->S.variant(s => Ok(s)) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#parse, `i=>{if(typeof i!=="string"){e[1](i)}return e[0](i)}`, ) }) test("Compiled serialize code snapshot", t => { - let struct = S.string->S.variant(s => Ok(s)) + let schema = S.string->S.variant(s => Ok(s)) t->U.assertCompiledCode( - ~struct, + ~schema, ~op=#serialize, `i=>{let v0;v0=i["TAG"];if(v0!==e[0]){e[1](v0)}return i["_0"]}`, ) }) -test("Works with variant struct used multiple times as a child struct", t => { - let appVersionSpecStruct = S.string->S.variant(current => {"current": current, "minimum": "1.0"}) +test("Works with variant schema used multiple times as a child schema", t => { + let appVersionSpecSchema = S.string->S.variant(current => {"current": current, "minimum": "1.0"}) - let appVersionsStruct = S.object(s => + let appVersionsSchema = S.object(s => { - "ios": s.field("ios", appVersionSpecStruct), - "android": s.field("android", appVersionSpecStruct), + "ios": s.field("ios", appVersionSpecSchema), + "android": s.field("android", appVersionSpecSchema), } ) @@ -157,12 +157,12 @@ test("Works with variant struct used multiple times as a child struct", t => { "android": {"current": "1.2", "minimum": "1.0"}, } - let value = rawAppVersions->S.parseAnyOrRaiseWith(appVersionsStruct) + let value = rawAppVersions->S.parseAnyOrRaiseWith(appVersionsSchema) t->Assert.deepEqual(value, appVersions, ()) - let data = appVersions->S.serializeOrRaiseWith(appVersionsStruct) + let data = appVersions->S.serializeOrRaiseWith(appVersionsSchema) t->Assert.deepEqual(data, rawAppVersions->Obj.magic, ()) - let data = appVersions->S.serializeOrRaiseWith(appVersionsStruct) + let data = appVersions->S.serializeOrRaiseWith(appVersionsSchema) t->Assert.deepEqual(data, rawAppVersions->Obj.magic, ()) }) diff --git a/packages/tests/src/genType/GenType.bs.mjs b/packages/tests/src/genType/GenType.bs.mjs index 13fd3e2a..885b9f6d 100644 --- a/packages/tests/src/genType/GenType.bs.mjs +++ b/packages/tests/src/genType/GenType.bs.mjs @@ -1,7 +1,7 @@ // Generated by ReScript, PLEASE EDIT WITH CARE import * as U from "../utils/U.bs.mjs"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; var error = U.error({ operation: "Parsing", @@ -9,13 +9,13 @@ var error = U.error({ TAG: "OperationFailed", _0: "Something went wrong" }, - path: S$RescriptStruct.Path.empty + path: S$RescriptSchema.Path.empty }); -var stringStruct = S$RescriptStruct.string; +var stringSchema = S$RescriptSchema.string; export { - stringStruct , + stringSchema , error , } /* error Not a pure module */ diff --git a/packages/tests/src/genType/GenType.gen.ts b/packages/tests/src/genType/GenType.gen.ts index 3222bbfc..83d0a0ce 100644 --- a/packages/tests/src/genType/GenType.gen.ts +++ b/packages/tests/src/genType/GenType.gen.ts @@ -6,10 +6,10 @@ import * as GenTypeBS__Es6Import from './GenType.bs'; const GenTypeBS: any = GenTypeBS__Es6Import; -import type {S_error as RescriptStruct_S_error} from 'rescript-struct/RescriptStruct.gen'; +import type {S_error as RescriptSchema_S_error} from 'rescript-schema/RescriptSchema.gen'; -import type {S_t as RescriptStruct_S_t} from 'rescript-struct/RescriptStruct.gen'; +import type {S_t as RescriptSchema_S_t} from 'rescript-schema/RescriptSchema.gen'; -export const stringStruct: RescriptStruct_S_t = GenTypeBS.stringStruct; +export const stringSchema: RescriptSchema_S_t = GenTypeBS.stringSchema; -export const error: RescriptStruct_S_error = GenTypeBS.error; +export const error: RescriptSchema_S_error = GenTypeBS.error; diff --git a/packages/tests/src/genType/GenType.res b/packages/tests/src/genType/GenType.res index e36e85fa..d33cb70c 100644 --- a/packages/tests/src/genType/GenType.res +++ b/packages/tests/src/genType/GenType.res @@ -1,5 +1,5 @@ @genType -let stringStruct = S.string +let stringSchema = S.string @genType let error: S.error = U.error({ diff --git a/packages/tests/src/genType/GenType_test_type.ts b/packages/tests/src/genType/GenType_test_type.ts index 51216116..c0019b72 100644 --- a/packages/tests/src/genType/GenType_test_type.ts +++ b/packages/tests/src/genType/GenType_test_type.ts @@ -3,6 +3,6 @@ import { expectType, TypeEqual } from "ts-expect"; import * as S from "../../../../src/S.js"; import * as GenType from "./GenType.gen"; -expectType>>( +expectType>>( true ); diff --git a/packages/tests/src/ppx/Ppx_Example_test.bs.mjs b/packages/tests/src/ppx/Ppx_Example_test.bs.mjs index cfb523a5..39534bcc 100644 --- a/packages/tests/src/ppx/Ppx_Example_test.bs.mjs +++ b/packages/tests/src/ppx/Ppx_Example_test.bs.mjs @@ -2,44 +2,44 @@ import * as U from "../utils/U.bs.mjs"; import Ava from "ava"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; -var ratingStruct = S$RescriptStruct.union([ - S$RescriptStruct.literal("G"), - S$RescriptStruct.literal("PG"), - S$RescriptStruct.literal("PG13"), - S$RescriptStruct.literal("R") +var ratingSchema = S$RescriptSchema.union([ + S$RescriptSchema.literal("G"), + S$RescriptSchema.literal("PG"), + S$RescriptSchema.literal("PG13"), + S$RescriptSchema.literal("R") ]); -var filmStruct = S$RescriptStruct.$$Object.factory(function (s) { +var filmSchema = S$RescriptSchema.$$Object.factory(function (s) { return { - Id: s.f("Id", S$RescriptStruct.$$float), - Title: s.f("Title", S$RescriptStruct.string), - Tags: s.f("Tags", S$RescriptStruct.$$Option.getOr(S$RescriptStruct.option(S$RescriptStruct.array(S$RescriptStruct.string)), [])), - Rating: s.f("Rating", ratingStruct), - Age: s.f("Age", S$RescriptStruct.deprecate(S$RescriptStruct.option(S$RescriptStruct.$$int), "Use rating instead")) + Id: s.f("Id", S$RescriptSchema.$$float), + Title: s.f("Title", S$RescriptSchema.string), + Tags: s.f("Tags", S$RescriptSchema.$$Option.getOr(S$RescriptSchema.option(S$RescriptSchema.array(S$RescriptSchema.string)), [])), + Rating: s.f("Rating", ratingSchema), + Age: s.f("Age", S$RescriptSchema.deprecate(S$RescriptSchema.option(S$RescriptSchema.$$int), "Use rating instead")) }; }); Ava("Example", (function (t) { - U.assertEqualStructs(t, filmStruct, S$RescriptStruct.object(function (s) { + U.assertEqualSchemas(t, filmSchema, S$RescriptSchema.object(function (s) { return { - Id: s.f("Id", S$RescriptStruct.$$float), - Title: s.f("Title", S$RescriptStruct.string), - Tags: s.o("Tags", S$RescriptStruct.array(S$RescriptStruct.string), []), - Rating: s.f("Rating", S$RescriptStruct.union([ - S$RescriptStruct.literal("G"), - S$RescriptStruct.literal("PG"), - S$RescriptStruct.literal("PG13"), - S$RescriptStruct.literal("R") + Id: s.f("Id", S$RescriptSchema.$$float), + Title: s.f("Title", S$RescriptSchema.string), + Tags: s.o("Tags", S$RescriptSchema.array(S$RescriptSchema.string), []), + Rating: s.f("Rating", S$RescriptSchema.union([ + S$RescriptSchema.literal("G"), + S$RescriptSchema.literal("PG"), + S$RescriptSchema.literal("PG13"), + S$RescriptSchema.literal("R") ])), - Age: s.f("Age", S$RescriptStruct.deprecate(S$RescriptStruct.option(S$RescriptStruct.$$int), "Use rating instead")) + Age: s.f("Age", S$RescriptSchema.deprecate(S$RescriptSchema.option(S$RescriptSchema.$$int), "Use rating instead")) }; }), undefined); })); export { - ratingStruct , - filmStruct , + ratingSchema , + filmSchema , } -/* ratingStruct Not a pure module */ +/* ratingSchema Not a pure module */ diff --git a/packages/tests/src/ppx/Ppx_Example_test.res b/packages/tests/src/ppx/Ppx_Example_test.res index 4e01489e..598cc516 100644 --- a/packages/tests/src/ppx/Ppx_Example_test.res +++ b/packages/tests/src/ppx/Ppx_Example_test.res @@ -1,29 +1,29 @@ open Ava open U -@struct +@schema type rating = | @as("G") GeneralAudiences | @as("PG") ParentalGuidanceSuggested | @as("PG13") ParentalStronglyCautioned | @as("R") Restricted -@struct +@schema type film = { @as("Id") id: float, @as("Title") title: string, @as("Tags") - tags: @struct(S.array(S.string)->S.option->S.Option.getOr([])) array, + tags: @schema(S.array(S.string)->S.option->S.Option.getOr([])) array, @as("Rating") rating: rating, @as("Age") - deprecatedAgeRestriction: @struct(S.int->S.option->S.deprecate("Use rating instead")) option, + deprecatedAgeRestriction: @schema(S.int->S.option->S.deprecate("Use rating instead")) option, } test("Example", t => { - t->assertEqualStructs( - filmStruct, + t->assertEqualSchemas( + filmSchema, S.object(s => { id: s.field("Id", S.float), title: s.field("Title", S.string), diff --git a/packages/tests/src/ppx/Ppx_General_test.bs.mjs b/packages/tests/src/ppx/Ppx_General_test.bs.mjs index 3137b9d6..de04815c 100644 --- a/packages/tests/src/ppx/Ppx_General_test.bs.mjs +++ b/packages/tests/src/ppx/Ppx_General_test.bs.mjs @@ -2,43 +2,43 @@ import * as U from "../utils/U.bs.mjs"; import Ava from "ava"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; -Ava("Creates struct with the name struct from t type", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.string, S$RescriptStruct.string, undefined); +Ava("Creates schema with the name schema from t type", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.string, S$RescriptSchema.string, undefined); })); -Ava("Creates struct with the type name and struct at the for non t types", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.$$int, S$RescriptStruct.$$int, undefined); +Ava("Creates schema with the type name and schema at the for non t types", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.$$int, S$RescriptSchema.$$int, undefined); })); -var reusedTypesStruct = S$RescriptStruct.tuple(function (s) { +var reusedTypesSchema = S$RescriptSchema.tuple(function (s) { return [ - s.i(0, S$RescriptStruct.string), - s.i(1, S$RescriptStruct.$$int), - s.i(2, S$RescriptStruct.bool), - s.i(3, S$RescriptStruct.$$float) + s.i(0, S$RescriptSchema.string), + s.i(1, S$RescriptSchema.$$int), + s.i(2, S$RescriptSchema.bool), + s.i(3, S$RescriptSchema.$$float) ]; }); -Ava("Can reuse structs from other types", (function (t) { - U.assertEqualStructs(t, reusedTypesStruct, S$RescriptStruct.tuple(function (s) { +Ava("Can reuse schemas from other types", (function (t) { + U.assertEqualSchemas(t, reusedTypesSchema, S$RescriptSchema.tuple(function (s) { return [ - s.i(0, S$RescriptStruct.string), - s.i(1, S$RescriptStruct.$$int), - s.i(2, S$RescriptStruct.bool), - s.i(3, S$RescriptStruct.$$float) + s.i(0, S$RescriptSchema.string), + s.i(1, S$RescriptSchema.$$int), + s.i(2, S$RescriptSchema.bool), + s.i(3, S$RescriptSchema.$$float) ]; }), undefined); })); -var struct = S$RescriptStruct.string; +var schema = S$RescriptSchema.string; -var fooStruct = S$RescriptStruct.$$int; +var fooSchema = S$RescriptSchema.$$int; export { - struct , - fooStruct , - reusedTypesStruct , + schema , + fooSchema , + reusedTypesSchema , } /* Not a pure module */ diff --git a/packages/tests/src/ppx/Ppx_General_test.res b/packages/tests/src/ppx/Ppx_General_test.res index 16c3700a..2e8f005b 100644 --- a/packages/tests/src/ppx/Ppx_General_test.res +++ b/packages/tests/src/ppx/Ppx_General_test.res @@ -1,27 +1,27 @@ open Ava open U -@struct +@schema type t = string -test("Creates struct with the name struct from t type", t => { - t->assertEqualStructs(struct, S.string) +test("Creates schema with the name schema from t type", t => { + t->assertEqualSchemas(schema, S.string) }) -@struct +@schema type foo = int -test("Creates struct with the type name and struct at the for non t types", t => { - t->assertEqualStructs(fooStruct, S.int) +test("Creates schema with the type name and schema at the for non t types", t => { + t->assertEqualSchemas(fooSchema, S.int) }) type bar = bool -@struct -type reusedTypes = (t, foo, @struct(S.bool) bar, float) -test("Can reuse structs from other types", t => { - t->assertEqualStructs( - reusedTypesStruct, - S.tuple(s => (s.item(0, struct), s.item(1, fooStruct), s.item(2, S.bool), s.item(3, S.float))), +@schema +type reusedTypes = (t, foo, @schema(S.bool) bar, float) +test("Can reuse schemas from other types", t => { + t->assertEqualSchemas( + reusedTypesSchema, + S.tuple(s => (s.item(0, schema), s.item(1, fooSchema), s.item(2, S.bool), s.item(3, S.float))), ) }) -// TODO: Support recursive structs +// TODO: Support recursive schemas diff --git a/packages/tests/src/ppx/Ppx_General_test.resi b/packages/tests/src/ppx/Ppx_General_test.resi index 920e0735..cf88c804 100644 --- a/packages/tests/src/ppx/Ppx_General_test.resi +++ b/packages/tests/src/ppx/Ppx_General_test.resi @@ -1,10 +1,10 @@ -@struct +@schema type t = string -@struct +@schema type foo type bar -@struct +@schema type reusedTypes = (t, foo, bar, float) diff --git a/packages/tests/src/ppx/Ppx_Polyvariants_test.bs.mjs b/packages/tests/src/ppx/Ppx_Polyvariants_test.bs.mjs index baff44e6..5fa414cc 100644 --- a/packages/tests/src/ppx/Ppx_Polyvariants_test.bs.mjs +++ b/packages/tests/src/ppx/Ppx_Polyvariants_test.bs.mjs @@ -2,41 +2,41 @@ import * as U from "../utils/U.bs.mjs"; import Ava from "ava"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; -var polyStruct = S$RescriptStruct.union([ - S$RescriptStruct.literal("one"), - S$RescriptStruct.literal("two") +var polySchema = S$RescriptSchema.union([ + S$RescriptSchema.literal("one"), + S$RescriptSchema.literal("two") ]); Ava("Polymorphic variant", (function (t) { - U.assertEqualStructs(t, polyStruct, S$RescriptStruct.union([ - S$RescriptStruct.literal("one"), - S$RescriptStruct.literal("two") + U.assertEqualSchemas(t, polySchema, S$RescriptSchema.union([ + S$RescriptSchema.literal("one"), + S$RescriptSchema.literal("two") ]), undefined); })); -var polyWithSingleItemStruct = S$RescriptStruct.literal("single"); +var polyWithSingleItemSchema = S$RescriptSchema.literal("single"); -Ava("Polymorphic variant with single item becomes a literal struct of the item", (function (t) { - U.assertEqualStructs(t, polyWithSingleItemStruct, S$RescriptStruct.literal("single"), undefined); +Ava("Polymorphic variant with single item becomes a literal schema of the item", (function (t) { + U.assertEqualSchemas(t, polyWithSingleItemSchema, S$RescriptSchema.literal("single"), undefined); })); -var polyWithAliasStruct = S$RescriptStruct.union([ - S$RescriptStruct.literal("one"), - S$RescriptStruct.literal("two") +var polyWithAliasSchema = S$RescriptSchema.union([ + S$RescriptSchema.literal("one"), + S$RescriptSchema.literal("two") ]); Ava("Polymorphic variant with partial @as usage", (function (t) { - U.assertEqualStructs(t, polyWithAliasStruct, S$RescriptStruct.union([ - S$RescriptStruct.literal("one"), - S$RescriptStruct.literal("two") + U.assertEqualSchemas(t, polyWithAliasSchema, S$RescriptSchema.union([ + S$RescriptSchema.literal("one"), + S$RescriptSchema.literal("two") ]), undefined); })); export { - polyStruct , - polyWithSingleItemStruct , - polyWithAliasStruct , + polySchema , + polyWithSingleItemSchema , + polyWithAliasSchema , } -/* polyStruct Not a pure module */ +/* polySchema Not a pure module */ diff --git a/packages/tests/src/ppx/Ppx_Polyvariants_test.res b/packages/tests/src/ppx/Ppx_Polyvariants_test.res index f75fbdb6..ff08c712 100644 --- a/packages/tests/src/ppx/Ppx_Polyvariants_test.res +++ b/packages/tests/src/ppx/Ppx_Polyvariants_test.res @@ -1,22 +1,22 @@ open Ava open U -@struct +@schema type poly = [#one | #two] test("Polymorphic variant", t => { - t->assertEqualStructs(polyStruct, S.union([S.literal(#one), S.literal(#two)])) + t->assertEqualSchemas(polySchema, S.union([S.literal(#one), S.literal(#two)])) }) -@struct +@schema type polyWithSingleItem = [#single] -test("Polymorphic variant with single item becomes a literal struct of the item", t => { - t->assertEqualStructs(polyWithSingleItemStruct, S.literal(#single)) +test("Polymorphic variant with single item becomes a literal schema of the item", t => { + t->assertEqualSchemas(polyWithSingleItemSchema, S.literal(#single)) }) -@struct +@schema type polyWithAlias = [@as(`하나`) #one | #two] test("Polymorphic variant with partial @as usage", t => { - t->assertEqualStructs(polyWithAliasStruct, S.union([S.literal(#one), S.literal(#two)])) + t->assertEqualSchemas(polyWithAliasSchema, S.union([S.literal(#one), S.literal(#two)])) }) // TODO: Support diff --git a/packages/tests/src/ppx/Ppx_Primitives_test.bs.mjs b/packages/tests/src/ppx/Ppx_Primitives_test.bs.mjs index c0f2dca0..87ebaeac 100644 --- a/packages/tests/src/ppx/Ppx_Primitives_test.bs.mjs +++ b/packages/tests/src/ppx/Ppx_Primitives_test.bs.mjs @@ -2,183 +2,183 @@ import * as U from "../utils/U.bs.mjs"; import Ava from "ava"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; -Ava("String struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.string, S$RescriptStruct.string, undefined); +Ava("String schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.string, S$RescriptSchema.string, undefined); })); -Ava("Int struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.$$int, S$RescriptStruct.$$int, undefined); +Ava("Int schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.$$int, S$RescriptSchema.$$int, undefined); })); -Ava("Float struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.$$float, S$RescriptStruct.$$float, undefined); +Ava("Float schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.$$float, S$RescriptSchema.$$float, undefined); })); -Ava("Bool struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.bool, S$RescriptStruct.bool, undefined); +Ava("Bool schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.bool, S$RescriptSchema.bool, undefined); })); -Ava("Unit struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.unit, S$RescriptStruct.unit, undefined); +Ava("Unit schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.unit, S$RescriptSchema.unit, undefined); })); -Ava("Unknown struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.unknown, S$RescriptStruct.unknown, undefined); +Ava("Unknown schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.unknown, S$RescriptSchema.unknown, undefined); })); -Ava("Never struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.never, S$RescriptStruct.never, undefined); +Ava("Never schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.never, S$RescriptSchema.never, undefined); })); -var myOptionOfStringStruct = S$RescriptStruct.option(S$RescriptStruct.string); +var myOptionOfStringSchema = S$RescriptSchema.option(S$RescriptSchema.string); -Ava("Option of string struct", (function (t) { - U.assertEqualStructs(t, myOptionOfStringStruct, S$RescriptStruct.option(S$RescriptStruct.string), undefined); +Ava("Option of string schema", (function (t) { + U.assertEqualSchemas(t, myOptionOfStringSchema, S$RescriptSchema.option(S$RescriptSchema.string), undefined); })); -var myArrayOfStringStruct = S$RescriptStruct.array(S$RescriptStruct.string); +var myArrayOfStringSchema = S$RescriptSchema.array(S$RescriptSchema.string); -Ava("Array of string struct", (function (t) { - U.assertEqualStructs(t, myArrayOfStringStruct, S$RescriptStruct.array(S$RescriptStruct.string), undefined); +Ava("Array of string schema", (function (t) { + U.assertEqualSchemas(t, myArrayOfStringSchema, S$RescriptSchema.array(S$RescriptSchema.string), undefined); })); -var myListOfStringStruct = S$RescriptStruct.list(S$RescriptStruct.string); +var myListOfStringSchema = S$RescriptSchema.list(S$RescriptSchema.string); -Ava("List of string struct", (function (t) { - U.assertEqualStructs(t, myListOfStringStruct, S$RescriptStruct.list(S$RescriptStruct.string), undefined); +Ava("List of string schema", (function (t) { + U.assertEqualSchemas(t, myListOfStringSchema, S$RescriptSchema.list(S$RescriptSchema.string), undefined); })); -var myDictOfStringStruct = S$RescriptStruct.dict(S$RescriptStruct.string); +var myDictOfStringSchema = S$RescriptSchema.dict(S$RescriptSchema.string); -Ava("Dict of string struct", (function (t) { - U.assertEqualStructs(t, myDictOfStringStruct, S$RescriptStruct.dict(S$RescriptStruct.string), undefined); +Ava("Dict of string schema", (function (t) { + U.assertEqualSchemas(t, myDictOfStringSchema, S$RescriptSchema.dict(S$RescriptSchema.string), undefined); })); -var myDictOfStringFromCoreStruct = S$RescriptStruct.dict(S$RescriptStruct.string); +var myDictOfStringFromCoreSchema = S$RescriptSchema.dict(S$RescriptSchema.string); -Ava("Dict of string struct from Core", (function (t) { - U.assertEqualStructs(t, myDictOfStringFromCoreStruct, S$RescriptStruct.dict(S$RescriptStruct.string), undefined); +Ava("Dict of string schema from Core", (function (t) { + U.assertEqualSchemas(t, myDictOfStringFromCoreSchema, S$RescriptSchema.dict(S$RescriptSchema.string), undefined); })); -Ava("Json struct", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.json, S$RescriptStruct.json, undefined); +Ava("Json schema", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.json, S$RescriptSchema.json, undefined); })); -Ava("Json struct from Core", (function (t) { - U.assertEqualStructs(t, S$RescriptStruct.json, S$RescriptStruct.json, undefined); +Ava("Json schema from Core", (function (t) { + U.assertEqualSchemas(t, S$RescriptSchema.json, S$RescriptSchema.json, undefined); })); -var myTupleStruct = S$RescriptStruct.tuple(function (s) { +var myTupleSchema = S$RescriptSchema.tuple(function (s) { return [ - s.i(0, S$RescriptStruct.string), - s.i(1, S$RescriptStruct.$$int) + s.i(0, S$RescriptSchema.string), + s.i(1, S$RescriptSchema.$$int) ]; }); -Ava("Tuple struct", (function (t) { - U.assertEqualStructs(t, myTupleStruct, S$RescriptStruct.tuple2(S$RescriptStruct.string, S$RescriptStruct.$$int), undefined); +Ava("Tuple schema", (function (t) { + U.assertEqualSchemas(t, myTupleSchema, S$RescriptSchema.tuple2(S$RescriptSchema.string, S$RescriptSchema.$$int), undefined); })); -var myBigTupleStruct = S$RescriptStruct.tuple(function (s) { +var myBigTupleSchema = S$RescriptSchema.tuple(function (s) { return [ - s.i(0, S$RescriptStruct.string), - s.i(1, S$RescriptStruct.string), - s.i(2, S$RescriptStruct.string), - s.i(3, S$RescriptStruct.$$int), - s.i(4, S$RescriptStruct.$$int), - s.i(5, S$RescriptStruct.$$int), - s.i(6, S$RescriptStruct.$$float), - s.i(7, S$RescriptStruct.$$float), - s.i(8, S$RescriptStruct.$$float), - s.i(9, S$RescriptStruct.bool), - s.i(10, S$RescriptStruct.bool), - s.i(11, S$RescriptStruct.bool) + s.i(0, S$RescriptSchema.string), + s.i(1, S$RescriptSchema.string), + s.i(2, S$RescriptSchema.string), + s.i(3, S$RescriptSchema.$$int), + s.i(4, S$RescriptSchema.$$int), + s.i(5, S$RescriptSchema.$$int), + s.i(6, S$RescriptSchema.$$float), + s.i(7, S$RescriptSchema.$$float), + s.i(8, S$RescriptSchema.$$float), + s.i(9, S$RescriptSchema.bool), + s.i(10, S$RescriptSchema.bool), + s.i(11, S$RescriptSchema.bool) ]; }); -Ava("Big tuple struct", (function (t) { - U.assertEqualStructs(t, myBigTupleStruct, S$RescriptStruct.tuple(function (s) { +Ava("Big tuple schema", (function (t) { + U.assertEqualSchemas(t, myBigTupleSchema, S$RescriptSchema.tuple(function (s) { return [ - s.i(0, S$RescriptStruct.string), - s.i(1, S$RescriptStruct.string), - s.i(2, S$RescriptStruct.string), - s.i(3, S$RescriptStruct.$$int), - s.i(4, S$RescriptStruct.$$int), - s.i(5, S$RescriptStruct.$$int), - s.i(6, S$RescriptStruct.$$float), - s.i(7, S$RescriptStruct.$$float), - s.i(8, S$RescriptStruct.$$float), - s.i(9, S$RescriptStruct.bool), - s.i(10, S$RescriptStruct.bool), - s.i(11, S$RescriptStruct.bool) + s.i(0, S$RescriptSchema.string), + s.i(1, S$RescriptSchema.string), + s.i(2, S$RescriptSchema.string), + s.i(3, S$RescriptSchema.$$int), + s.i(4, S$RescriptSchema.$$int), + s.i(5, S$RescriptSchema.$$int), + s.i(6, S$RescriptSchema.$$float), + s.i(7, S$RescriptSchema.$$float), + s.i(8, S$RescriptSchema.$$float), + s.i(9, S$RescriptSchema.bool), + s.i(10, S$RescriptSchema.bool), + s.i(11, S$RescriptSchema.bool) ]; }), undefined); })); -var myCustomStringStruct = S$RescriptStruct.$$String.email(S$RescriptStruct.string, undefined); +var myCustomStringSchema = S$RescriptSchema.$$String.email(S$RescriptSchema.string, undefined); -Ava("Custom string struct", (function (t) { - U.assertEqualStructs(t, myCustomStringStruct, S$RescriptStruct.$$String.email(S$RescriptStruct.string, undefined), undefined); +Ava("Custom string schema", (function (t) { + U.assertEqualSchemas(t, myCustomStringSchema, S$RescriptSchema.$$String.email(S$RescriptSchema.string, undefined), undefined); })); -var myCustomLiteralStringStruct = S$RescriptStruct.$$String.email(S$RescriptStruct.literal("123"), undefined); +var myCustomLiteralStringSchema = S$RescriptSchema.$$String.email(S$RescriptSchema.literal("123"), undefined); -Ava("Custom litaral string struct", (function (t) { - U.assertEqualStructs(t, myCustomLiteralStringStruct, S$RescriptStruct.$$String.email(S$RescriptStruct.literal("123"), undefined), undefined); +Ava("Custom litaral string schema", (function (t) { + U.assertEqualSchemas(t, myCustomLiteralStringSchema, S$RescriptSchema.$$String.email(S$RescriptSchema.literal("123"), undefined), undefined); })); -var myCustomOptionalStringStruct = S$RescriptStruct.option(S$RescriptStruct.$$String.email(S$RescriptStruct.string, undefined)); +var myCustomOptionalStringSchema = S$RescriptSchema.option(S$RescriptSchema.$$String.email(S$RescriptSchema.string, undefined)); -Ava("Custom optional string struct", (function (t) { - U.assertEqualStructs(t, myCustomOptionalStringStruct, S$RescriptStruct.option(S$RescriptStruct.$$String.email(S$RescriptStruct.string, undefined)), undefined); +Ava("Custom optional string schema", (function (t) { + U.assertEqualSchemas(t, myCustomOptionalStringSchema, S$RescriptSchema.option(S$RescriptSchema.$$String.email(S$RescriptSchema.string, undefined)), undefined); })); -var myNullOfStringStruct = S$RescriptStruct.$$null(S$RescriptStruct.string); +var myNullOfStringSchema = S$RescriptSchema.$$null(S$RescriptSchema.string); -Ava("Null of string struct", (function (t) { - U.assertEqualStructs(t, myNullOfStringStruct, S$RescriptStruct.$$null(S$RescriptStruct.string), undefined); +Ava("Null of string schema", (function (t) { + U.assertEqualSchemas(t, myNullOfStringSchema, S$RescriptSchema.$$null(S$RescriptSchema.string), undefined); })); -var myStringStruct = S$RescriptStruct.string; +var myStringSchema = S$RescriptSchema.string; -var myIntStruct = S$RescriptStruct.$$int; +var myIntSchema = S$RescriptSchema.$$int; -var myFloatStruct = S$RescriptStruct.$$float; +var myFloatSchema = S$RescriptSchema.$$float; -var myBoolStruct = S$RescriptStruct.bool; +var myBoolSchema = S$RescriptSchema.bool; -var myUnitStruct = S$RescriptStruct.unit; +var myUnitSchema = S$RescriptSchema.unit; -var myUnknownStruct = S$RescriptStruct.unknown; +var myUnknownSchema = S$RescriptSchema.unknown; -var myNeverStruct = S$RescriptStruct.never; +var myNeverSchema = S$RescriptSchema.never; -var myJsonStruct = S$RescriptStruct.json; +var myJsonSchema = S$RescriptSchema.json; -var myJsonFromCoreStruct = S$RescriptStruct.json; +var myJsonFromCoreSchema = S$RescriptSchema.json; export { - myStringStruct , - myIntStruct , - myFloatStruct , - myBoolStruct , - myUnitStruct , - myUnknownStruct , - myNeverStruct , - myOptionOfStringStruct , - myArrayOfStringStruct , - myListOfStringStruct , - myDictOfStringStruct , - myDictOfStringFromCoreStruct , - myJsonStruct , - myJsonFromCoreStruct , - myTupleStruct , - myBigTupleStruct , - myCustomStringStruct , - myCustomLiteralStringStruct , - myCustomOptionalStringStruct , - myNullOfStringStruct , + myStringSchema , + myIntSchema , + myFloatSchema , + myBoolSchema , + myUnitSchema , + myUnknownSchema , + myNeverSchema , + myOptionOfStringSchema , + myArrayOfStringSchema , + myListOfStringSchema , + myDictOfStringSchema , + myDictOfStringFromCoreSchema , + myJsonSchema , + myJsonFromCoreSchema , + myTupleSchema , + myBigTupleSchema , + myCustomStringSchema , + myCustomLiteralStringSchema , + myCustomOptionalStringSchema , + myNullOfStringSchema , } /* Not a pure module */ diff --git a/packages/tests/src/ppx/Ppx_Primitives_test.res b/packages/tests/src/ppx/Ppx_Primitives_test.res index a1b5cfbc..20489a74 100644 --- a/packages/tests/src/ppx/Ppx_Primitives_test.res +++ b/packages/tests/src/ppx/Ppx_Primitives_test.res @@ -2,101 +2,101 @@ open Ava open RescriptCore open U -@struct +@schema type myString = string -test("String struct", t => { - t->assertEqualStructs(myStringStruct, S.string) +test("String schema", t => { + t->assertEqualSchemas(myStringSchema, S.string) }) -@struct +@schema type myInt = int -test("Int struct", t => { - t->assertEqualStructs(myIntStruct, S.int) +test("Int schema", t => { + t->assertEqualSchemas(myIntSchema, S.int) }) -@struct +@schema type myFloat = float -test("Float struct", t => { - t->assertEqualStructs(myFloatStruct, S.float) +test("Float schema", t => { + t->assertEqualSchemas(myFloatSchema, S.float) }) -@struct +@schema type myBool = bool -test("Bool struct", t => { - t->assertEqualStructs(myBoolStruct, S.bool) +test("Bool schema", t => { + t->assertEqualSchemas(myBoolSchema, S.bool) }) -@struct +@schema type myUnit = unit -test("Unit struct", t => { - t->assertEqualStructs(myUnitStruct, S.unit) +test("Unit schema", t => { + t->assertEqualSchemas(myUnitSchema, S.unit) }) -@struct +@schema type myUnknown = unknown -test("Unknown struct", t => { - t->assertEqualStructs(myUnknownStruct, S.unknown) +test("Unknown schema", t => { + t->assertEqualSchemas(myUnknownSchema, S.unknown) }) -@struct +@schema type myNever = S.never -test("Never struct", t => { - t->assertEqualStructs(myNeverStruct, S.never) +test("Never schema", t => { + t->assertEqualSchemas(myNeverSchema, S.never) }) -@struct +@schema type myOptionOfString = option -test("Option of string struct", t => { - t->assertEqualStructs(myOptionOfStringStruct, S.option(S.string)) +test("Option of string schema", t => { + t->assertEqualSchemas(myOptionOfStringSchema, S.option(S.string)) }) -@struct +@schema type myArrayOfString = array -test("Array of string struct", t => { - t->assertEqualStructs(myArrayOfStringStruct, S.array(S.string)) +test("Array of string schema", t => { + t->assertEqualSchemas(myArrayOfStringSchema, S.array(S.string)) }) -@struct +@schema type myListOfString = list -test("List of string struct", t => { - t->assertEqualStructs(myListOfStringStruct, S.list(S.string)) +test("List of string schema", t => { + t->assertEqualSchemas(myListOfStringSchema, S.list(S.string)) }) -@struct +@schema type myDictOfString = Js.Dict.t -test("Dict of string struct", t => { - t->assertEqualStructs(myDictOfStringStruct, S.dict(S.string)) +test("Dict of string schema", t => { + t->assertEqualSchemas(myDictOfStringSchema, S.dict(S.string)) }) -@struct +@schema type myDictOfStringFromCore = Dict.t -test("Dict of string struct from Core", t => { - t->assertEqualStructs(myDictOfStringFromCoreStruct, S.dict(S.string)) +test("Dict of string schema from Core", t => { + t->assertEqualSchemas(myDictOfStringFromCoreSchema, S.dict(S.string)) }) -@struct +@schema type myJson = Js.Json.t -test("Json struct", t => { - t->assertEqualStructs(myJsonStruct, S.json) +test("Json schema", t => { + t->assertEqualSchemas(myJsonSchema, S.json) }) -@struct +@schema type myJsonFromCore = JSON.t -test("Json struct from Core", t => { - t->assertEqualStructs(myJsonFromCoreStruct, S.json) +test("Json schema from Core", t => { + t->assertEqualSchemas(myJsonFromCoreSchema, S.json) }) -@struct +@schema type myTuple = (string, int) -test("Tuple struct", t => { - t->assertEqualStructs(myTupleStruct, S.tuple2(S.string, S.int)) +test("Tuple schema", t => { + t->assertEqualSchemas(myTupleSchema, S.tuple2(S.string, S.int)) }) -@struct +@schema type myBigTuple = (string, string, string, int, int, int, float, float, float, bool, bool, bool) -test("Big tuple struct", t => { - t->assertEqualStructs( - myBigTupleStruct, +test("Big tuple schema", t => { + t->assertEqualSchemas( + myBigTupleSchema, S.tuple(s => ( s.item(0, S.string), s.item(1, S.string), @@ -114,31 +114,31 @@ test("Big tuple struct", t => { ) }) -@struct -type myCustomString = @struct(S.string->S.String.email) string -test("Custom string struct", t => { - t->assertEqualStructs(myCustomStringStruct, S.string->S.String.email) +@schema +type myCustomString = @schema(S.string->S.String.email) string +test("Custom string schema", t => { + t->assertEqualSchemas(myCustomStringSchema, S.string->S.String.email) }) -@struct -type myCustomLiteralString = @struct(S.literal("123")->S.String.email) string -test("Custom litaral string struct", t => { - t->assertEqualStructs(myCustomLiteralStringStruct, S.literal("123")->S.String.email) +@schema +type myCustomLiteralString = @schema(S.literal("123")->S.String.email) string +test("Custom litaral string schema", t => { + t->assertEqualSchemas(myCustomLiteralStringSchema, S.literal("123")->S.String.email) }) -@struct -type myCustomOptionalString = option<@struct(S.string->S.String.email) string> -test("Custom optional string struct", t => { - t->assertEqualStructs(myCustomOptionalStringStruct, S.string->S.String.email->S.option) +@schema +type myCustomOptionalString = option<@schema(S.string->S.String.email) string> +test("Custom optional string schema", t => { + t->assertEqualSchemas(myCustomOptionalStringSchema, S.string->S.String.email->S.option) }) -// @struct +// @schema // type myNullOfString = null // This will result with error: // The incompatible parts: option vs myNullOfString (defined as null) // So use the code below instead -@struct -type myNullOfString = @struct(S.null(S.string)) option -test("Null of string struct", t => { - t->assertEqualStructs(myNullOfStringStruct, S.null(S.string)) +@schema +type myNullOfString = @schema(S.null(S.string)) option +test("Null of string schema", t => { + t->assertEqualSchemas(myNullOfStringSchema, S.null(S.string)) }) diff --git a/packages/tests/src/ppx/Ppx_Records_test.bs.mjs b/packages/tests/src/ppx/Ppx_Records_test.bs.mjs index 9450ae35..de73f98c 100644 --- a/packages/tests/src/ppx/Ppx_Records_test.bs.mjs +++ b/packages/tests/src/ppx/Ppx_Records_test.bs.mjs @@ -2,23 +2,23 @@ import * as U from "../utils/U.bs.mjs"; import Ava from "ava"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; -var simpleRecordStruct = S$RescriptStruct.$$Object.factory(function (s) { +var simpleRecordSchema = S$RescriptSchema.$$Object.factory(function (s) { return { - label: s.f("label", S$RescriptStruct.string), - value: s.f("value", S$RescriptStruct.$$int) + label: s.f("label", S$RescriptSchema.string), + value: s.f("value", S$RescriptSchema.$$int) }; }); -Ava("Simple record struct", (function (t) { - U.assertEqualStructs(t, simpleRecordStruct, S$RescriptStruct.object(function (s) { +Ava("Simple record schema", (function (t) { + U.assertEqualSchemas(t, simpleRecordSchema, S$RescriptSchema.object(function (s) { return { - label: s.f("label", S$RescriptStruct.string), - value: s.f("value", S$RescriptStruct.$$int) + label: s.f("label", S$RescriptSchema.string), + value: s.f("value", S$RescriptSchema.$$int) }; }), undefined); - t.deepEqual(S$RescriptStruct.parseWith({label:"foo",value:1}, simpleRecordStruct), { + t.deepEqual(S$RescriptSchema.parseWith({label:"foo",value:1}, simpleRecordSchema), { TAG: "Ok", _0: { label: "foo", @@ -27,21 +27,21 @@ Ava("Simple record struct", (function (t) { }, undefined); })); -var recordWithAliasStruct = S$RescriptStruct.$$Object.factory(function (s) { +var recordWithAliasSchema = S$RescriptSchema.$$Object.factory(function (s) { return { - "aliased-label": s.f("aliased-label", S$RescriptStruct.string), - value: s.f("value", S$RescriptStruct.$$int) + "aliased-label": s.f("aliased-label", S$RescriptSchema.string), + value: s.f("value", S$RescriptSchema.$$int) }; }); -Ava("Record struct with alias for field name", (function (t) { - U.assertEqualStructs(t, recordWithAliasStruct, S$RescriptStruct.object(function (s) { +Ava("Record schema with alias for field name", (function (t) { + U.assertEqualSchemas(t, recordWithAliasSchema, S$RescriptSchema.object(function (s) { return { - "aliased-label": s.f("aliased-label", S$RescriptStruct.string), - value: s.f("value", S$RescriptStruct.$$int) + "aliased-label": s.f("aliased-label", S$RescriptSchema.string), + value: s.f("value", S$RescriptSchema.$$int) }; }), undefined); - t.deepEqual(S$RescriptStruct.parseWith({"aliased-label":"foo",value:1}, recordWithAliasStruct), { + t.deepEqual(S$RescriptSchema.parseWith({"aliased-label":"foo",value:1}, recordWithAliasSchema), { TAG: "Ok", _0: { "aliased-label": "foo", @@ -50,28 +50,28 @@ Ava("Record struct with alias for field name", (function (t) { }, undefined); })); -var recordWithOptionalStruct = S$RescriptStruct.$$Object.factory(function (s) { +var recordWithOptionalSchema = S$RescriptSchema.$$Object.factory(function (s) { return { - label: s.f("label", S$RescriptStruct.option(S$RescriptStruct.string)), - value: s.f("value", S$RescriptStruct.option(S$RescriptStruct.$$int)) + label: s.f("label", S$RescriptSchema.option(S$RescriptSchema.string)), + value: s.f("value", S$RescriptSchema.option(S$RescriptSchema.$$int)) }; }); -Ava("Record struct with optional fields", (function (t) { - U.assertEqualStructs(t, recordWithOptionalStruct, S$RescriptStruct.object(function (s) { +Ava("Record schema with optional fields", (function (t) { + U.assertEqualSchemas(t, recordWithOptionalSchema, S$RescriptSchema.object(function (s) { return { - label: s.f("label", S$RescriptStruct.option(S$RescriptStruct.string)), - value: s.f("value", S$RescriptStruct.option(S$RescriptStruct.$$int)) + label: s.f("label", S$RescriptSchema.option(S$RescriptSchema.string)), + value: s.f("value", S$RescriptSchema.option(S$RescriptSchema.$$int)) }; }), undefined); - t.deepEqual(S$RescriptStruct.parseWith({"label":"foo",value:1}, recordWithOptionalStruct), { + t.deepEqual(S$RescriptSchema.parseWith({"label":"foo",value:1}, recordWithOptionalSchema), { TAG: "Ok", _0: { label: "foo", value: 1 } }, undefined); - t.deepEqual(S$RescriptStruct.parseWith({}, recordWithOptionalStruct), { + t.deepEqual(S$RescriptSchema.parseWith({}, recordWithOptionalSchema), { TAG: "Ok", _0: { label: undefined, @@ -81,8 +81,8 @@ Ava("Record struct with optional fields", (function (t) { })); export { - simpleRecordStruct , - recordWithAliasStruct , - recordWithOptionalStruct , + simpleRecordSchema , + recordWithAliasSchema , + recordWithOptionalSchema , } -/* simpleRecordStruct Not a pure module */ +/* simpleRecordSchema Not a pure module */ diff --git a/packages/tests/src/ppx/Ppx_Records_test.res b/packages/tests/src/ppx/Ppx_Records_test.res index 776963cb..53aa32ef 100644 --- a/packages/tests/src/ppx/Ppx_Records_test.res +++ b/packages/tests/src/ppx/Ppx_Records_test.res @@ -1,66 +1,66 @@ open Ava open U -@struct +@schema type simpleRecord = { label: string, value: int, } -test("Simple record struct", t => { - t->assertEqualStructs( - simpleRecordStruct, +test("Simple record schema", t => { + t->assertEqualSchemas( + simpleRecordSchema, S.object(s => { label: s.field("label", S.string), value: s.field("value", S.int), }), ) t->Assert.deepEqual( - %raw(`{label:"foo",value:1}`)->S.parseWith(simpleRecordStruct), + %raw(`{label:"foo",value:1}`)->S.parseWith(simpleRecordSchema), Ok({label: "foo", value: 1}), (), ) }) -@struct +@schema type recordWithAlias = { @as("aliased-label") label: string, value: int, } -test("Record struct with alias for field name", t => { - t->assertEqualStructs( - recordWithAliasStruct, +test("Record schema with alias for field name", t => { + t->assertEqualSchemas( + recordWithAliasSchema, S.object(s => { label: s.field("aliased-label", S.string), value: s.field("value", S.int), }), ) t->Assert.deepEqual( - %raw(`{"aliased-label":"foo",value:1}`)->S.parseWith(recordWithAliasStruct), + %raw(`{"aliased-label":"foo",value:1}`)->S.parseWith(recordWithAliasSchema), Ok({label: "foo", value: 1}), (), ) }) -@struct +@schema type recordWithOptional = { label: option, value?: int, } -test("Record struct with optional fields", t => { - t->assertEqualStructs( - recordWithOptionalStruct, +test("Record schema with optional fields", t => { + t->assertEqualSchemas( + recordWithOptionalSchema, S.object(s => { label: s.field("label", S.option(S.string)), value: ?s.field("value", S.option(S.int)), }), ) t->Assert.deepEqual( - %raw(`{"label":"foo",value:1}`)->S.parseWith(recordWithOptionalStruct), + %raw(`{"label":"foo",value:1}`)->S.parseWith(recordWithOptionalSchema), Ok({label: Some("foo"), value: 1}), (), ) t->Assert.deepEqual( - %raw(`{}`)->S.parseWith(recordWithOptionalStruct), + %raw(`{}`)->S.parseWith(recordWithOptionalSchema), Ok({label: %raw(`undefined`), value: %raw(`undefined`)}), (), ) diff --git a/packages/tests/src/ppx/Ppx_Variants_test.bs.mjs b/packages/tests/src/ppx/Ppx_Variants_test.bs.mjs index ccc80463..cabf5f68 100644 --- a/packages/tests/src/ppx/Ppx_Variants_test.bs.mjs +++ b/packages/tests/src/ppx/Ppx_Variants_test.bs.mjs @@ -2,41 +2,41 @@ import * as U from "../utils/U.bs.mjs"; import Ava from "ava"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; -var variantStruct = S$RescriptStruct.union([ - S$RescriptStruct.literal("One"), - S$RescriptStruct.literal("Two") +var variantSchema = S$RescriptSchema.union([ + S$RescriptSchema.literal("One"), + S$RescriptSchema.literal("Two") ]); Ava("Variant", (function (t) { - U.assertEqualStructs(t, variantStruct, S$RescriptStruct.union([ - S$RescriptStruct.literal("One"), - S$RescriptStruct.literal("Two") + U.assertEqualSchemas(t, variantSchema, S$RescriptSchema.union([ + S$RescriptSchema.literal("One"), + S$RescriptSchema.literal("Two") ]), undefined); })); -var variantWithSingleItemStruct = S$RescriptStruct.literal("Single"); +var variantWithSingleItemSchema = S$RescriptSchema.literal("Single"); -Ava("Variant with single item becomes a literal struct of the item", (function (t) { - U.assertEqualStructs(t, variantWithSingleItemStruct, S$RescriptStruct.literal("Single"), undefined); +Ava("Variant with single item becomes a literal schema of the item", (function (t) { + U.assertEqualSchemas(t, variantWithSingleItemSchema, S$RescriptSchema.literal("Single"), undefined); })); -var variantWithAliasStruct = S$RescriptStruct.union([ - S$RescriptStruct.literal("하나"), - S$RescriptStruct.literal("Two") +var variantWithAliasSchema = S$RescriptSchema.union([ + S$RescriptSchema.literal("하나"), + S$RescriptSchema.literal("Two") ]); Ava("Variant with partial @as usage", (function (t) { - U.assertEqualStructs(t, variantWithAliasStruct, S$RescriptStruct.union([ - S$RescriptStruct.literal("하나"), - S$RescriptStruct.literal("Two") + U.assertEqualSchemas(t, variantWithAliasSchema, S$RescriptSchema.union([ + S$RescriptSchema.literal("하나"), + S$RescriptSchema.literal("Two") ]), undefined); })); export { - variantStruct , - variantWithSingleItemStruct , - variantWithAliasStruct , + variantSchema , + variantWithSingleItemSchema , + variantWithAliasSchema , } -/* variantStruct Not a pure module */ +/* variantSchema Not a pure module */ diff --git a/packages/tests/src/ppx/Ppx_Variants_test.res b/packages/tests/src/ppx/Ppx_Variants_test.res index de0463a0..fd7e954c 100644 --- a/packages/tests/src/ppx/Ppx_Variants_test.res +++ b/packages/tests/src/ppx/Ppx_Variants_test.res @@ -1,30 +1,30 @@ open Ava open U -@struct +@schema type variant = One | Two test("Variant", t => { - t->assertEqualStructs(variantStruct, S.union([S.literal(One), S.literal(Two)])) + t->assertEqualSchemas(variantSchema, S.union([S.literal(One), S.literal(Two)])) }) -@struct +@schema type variantWithSingleItem = Single -test("Variant with single item becomes a literal struct of the item", t => { - t->assertEqualStructs(variantWithSingleItemStruct, S.literal(Single)) +test("Variant with single item becomes a literal schema of the item", t => { + t->assertEqualSchemas(variantWithSingleItemSchema, S.literal(Single)) }) -@struct +@schema type variantWithAlias = | @as(`하나`) One | Two test("Variant with partial @as usage", t => { - t->assertEqualStructs(variantWithAliasStruct, S.union([S.literal(One), S.literal(Two)])) + t->assertEqualSchemas(variantWithAliasSchema, S.union([S.literal(One), S.literal(Two)])) }) // TODO: Support -// @struct +// @schema // type variantWithPayloads = Constant | SinglePayload(int) // test("Variant with tuple payloads", t => { -// t->assertEqualStructs( -// variantWithPayloadsStruct, +// t->assertEqualSchemas( +// variantWithPayloadsSchema, // S.union([S.literal(Constant), S.unknown->Obj.magic]), // ) // }) diff --git a/packages/tests/src/utils/U.bs.mjs b/packages/tests/src/utils/U.bs.mjs index 6603713e..b46d83d1 100644 --- a/packages/tests/src/utils/U.bs.mjs +++ b/packages/tests/src/utils/U.bs.mjs @@ -2,7 +2,7 @@ import * as Caml_option from "rescript/lib/es6/caml_option.js"; import * as Caml_exceptions from "rescript/lib/es6/caml_exceptions.js"; -import * as S$RescriptStruct from "rescript-struct/src/S.bs.mjs"; +import * as S$RescriptSchema from "rescript-schema/src/S.bs.mjs"; import * as Caml_js_exceptions from "rescript/lib/es6/caml_js_exceptions.js"; function unsafeGetVariantPayload(variant) { @@ -19,7 +19,7 @@ function raiseTestException() { } function error(param) { - return S$RescriptStruct.$$Error.make(param.code, param.operation, param.path); + return S$RescriptSchema.$$Error.make(param.code, param.operation, param.path); } function assertThrowsTestException(t, fn, message, param) { @@ -38,9 +38,9 @@ function assertThrowsTestException(t, fn, message, param) { } } -function cleanUpStruct(struct) { +function cleanUpSchema(schema) { var $$new = {}; - Object.entries(struct).forEach(function (param) { + Object.entries(schema).forEach(function (param) { var value = param[1]; var key = param[0]; switch (key) { @@ -52,7 +52,7 @@ function cleanUpStruct(struct) { return ; default: if (typeof value === "object" && value !== null) { - $$new[key] = cleanUpStruct(value); + $$new[key] = cleanUpSchema(value); } else { $$new[key] = value; } @@ -62,55 +62,55 @@ function cleanUpStruct(struct) { return $$new; } -function unsafeAssertEqualStructs(t, s1, s2, message) { - t.deepEqual(cleanUpStruct(s1), cleanUpStruct(s2), message !== undefined ? Caml_option.valFromOption(message) : undefined); +function unsafeAssertEqualSchemas(t, s1, s2, message) { + t.deepEqual(cleanUpSchema(s1), cleanUpSchema(s2), message !== undefined ? Caml_option.valFromOption(message) : undefined); } -function assertCompiledCode(t, struct, op, code, message) { +function assertCompiledCode(t, schema, op, code, message) { var compiledCode; if (op === "parse") { - if (S$RescriptStruct.isAsyncParse(struct)) { - S$RescriptStruct.parseAsyncInStepsWith(undefined, struct); - compiledCode = (struct.opa.toString()); + if (S$RescriptSchema.isAsyncParse(schema)) { + S$RescriptSchema.parseAsyncInStepsWith(undefined, schema); + compiledCode = (schema.opa.toString()); } else { - S$RescriptStruct.parseAnyWith(undefined, struct); - compiledCode = (struct.op.toString()); + S$RescriptSchema.parseAnyWith(undefined, schema); + compiledCode = (schema.op.toString()); } } else { try { - S$RescriptStruct.serializeToUnknownOrRaiseWith(undefined, struct); + S$RescriptSchema.serializeToUnknownOrRaiseWith(undefined, schema); } catch (exn){ } - compiledCode = (struct.os.toString()); + compiledCode = (schema.os.toString()); } t.is(compiledCode, code, message !== undefined ? Caml_option.valFromOption(message) : undefined); } -function assertCompiledCodeIsNoop(t, struct, op, message) { +function assertCompiledCodeIsNoop(t, schema, op, message) { var compiledCode; if (op === "parse") { - if (S$RescriptStruct.isAsyncParse(struct)) { - S$RescriptStruct.parseAsyncInStepsWith(undefined, struct); - compiledCode = (struct.opa.toString()); + if (S$RescriptSchema.isAsyncParse(schema)) { + S$RescriptSchema.parseAsyncInStepsWith(undefined, schema); + compiledCode = (schema.opa.toString()); } else { - S$RescriptStruct.parseAnyWith(undefined, struct); - compiledCode = (struct.op.toString()); + S$RescriptSchema.parseAnyWith(undefined, schema); + compiledCode = (schema.op.toString()); } } else { try { - S$RescriptStruct.serializeToUnknownOrRaiseWith(undefined, struct); + S$RescriptSchema.serializeToUnknownOrRaiseWith(undefined, schema); } catch (exn){ } - compiledCode = (struct.os.toString()); + compiledCode = (schema.os.toString()); } t.truthy(compiledCode.startsWith("function noopOperation(i)"), message !== undefined ? Caml_option.valFromOption(message) : undefined); } -var assertEqualStructs = unsafeAssertEqualStructs; +var assertEqualSchemas = unsafeAssertEqualSchemas; export { unsafeGetVariantPayload , @@ -118,10 +118,10 @@ export { raiseTestException , error , assertThrowsTestException , - cleanUpStruct , - unsafeAssertEqualStructs , + cleanUpSchema , + unsafeAssertEqualSchemas , assertCompiledCode , assertCompiledCodeIsNoop , - assertEqualStructs , + assertEqualSchemas , } -/* S-RescriptStruct Not a pure module */ +/* S-RescriptSchema Not a pure module */ diff --git a/packages/tests/src/utils/U.res b/packages/tests/src/utils/U.res index 923a169c..7c94c8d0 100644 --- a/packages/tests/src/utils/U.res +++ b/packages/tests/src/utils/U.res @@ -29,9 +29,9 @@ let assertThrowsTestException = { } } -let rec cleanUpStruct = struct => { +let rec cleanUpSchema = schema => { let new = Dict.make() - struct + schema ->(magic: S.t<'a> => Dict.t) ->Dict.toArray ->Array.forEach(((key, value)) => { @@ -41,7 +41,7 @@ let rec cleanUpStruct = struct => { if typeof(value) === #object && value !== %raw(`null`) { new->Dict.set( key, - cleanUpStruct(value->(magic: unknown => S.t<'a>))->(magic: S.t<'a> => unknown), + cleanUpSchema(value->(magic: unknown => S.t<'a>))->(magic: S.t<'a> => unknown), ) } else { new->Dict.set(key, value) @@ -51,57 +51,57 @@ let rec cleanUpStruct = struct => { new->(magic: Dict.t => S.t<'a>) } -let unsafeAssertEqualStructs = (t, s1: S.t<'v1>, s2: S.t<'v2>, ~message=?) => { - t->Assert.unsafeDeepEqual(s1->cleanUpStruct, s2->cleanUpStruct, ~message?, ()) +let unsafeAssertEqualSchemas = (t, s1: S.t<'v1>, s2: S.t<'v2>, ~message=?) => { + t->Assert.unsafeDeepEqual(s1->cleanUpSchema, s2->cleanUpSchema, ~message?, ()) } -let assertCompiledCode = (t, ~struct, ~op: [#parse | #serialize], code, ~message=?) => { +let assertCompiledCode = (t, ~schema, ~op: [#parse | #serialize], code, ~message=?) => { let compiledCode = switch op { | #parse => - if struct->S.isAsyncParse { - let _ = %raw(`undefined`)->S.parseAsyncInStepsWith(struct) - %raw(`struct.opa.toString()`) + if schema->S.isAsyncParse { + let _ = %raw(`undefined`)->S.parseAsyncInStepsWith(schema) + %raw(`schema.opa.toString()`) } else { - let _ = %raw(`undefined`)->S.parseAnyWith(struct) - %raw(`struct.op.toString()`) + let _ = %raw(`undefined`)->S.parseAnyWith(schema) + %raw(`schema.op.toString()`) } | #serialize => { try { - let _ = %raw(`undefined`)->S.serializeToUnknownOrRaiseWith(struct) + let _ = %raw(`undefined`)->S.serializeToUnknownOrRaiseWith(schema) } catch { | _ => () } - %raw(`struct.os.toString()`) + %raw(`schema.os.toString()`) } } t->Assert.is(compiledCode, code, ~message?, ()) } -let assertCompiledCodeIsNoop = (t, ~struct, ~op: [#parse | #serialize], ~message=?) => { +let assertCompiledCodeIsNoop = (t, ~schema, ~op: [#parse | #serialize], ~message=?) => { let compiledCode = switch op { | #parse => - if struct->S.isAsyncParse { - let _ = %raw(`undefined`)->S.parseAsyncInStepsWith(struct) - %raw(`struct.opa.toString()`) + if schema->S.isAsyncParse { + let _ = %raw(`undefined`)->S.parseAsyncInStepsWith(schema) + %raw(`schema.opa.toString()`) } else { - let _ = %raw(`undefined`)->S.parseAnyWith(struct) - %raw(`struct.op.toString()`) + let _ = %raw(`undefined`)->S.parseAnyWith(schema) + %raw(`schema.op.toString()`) } | #serialize => { try { - let _ = %raw(`undefined`)->S.serializeToUnknownOrRaiseWith(struct) + let _ = %raw(`undefined`)->S.serializeToUnknownOrRaiseWith(schema) } catch { | _ => () } - %raw(`struct.os.toString()`) + %raw(`schema.os.toString()`) } } t->Assert.truthy(compiledCode->String.startsWith("function noopOperation(i)"), ~message?, ()) } -let assertEqualStructs: ( +let assertEqualSchemas: ( Ava.ExecutionContext.t<'a>, S.t<'value>, S.t<'value>, ~message: string=?, -) => unit = unsafeAssertEqualStructs +) => unit = unsafeAssertEqualSchemas diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a941c4dc..76f78b34 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -10,8 +10,8 @@ importers: benchmark: 2.1.4 c8: 7.12.0 rescript: 11.0.0-rc.5 + rescript-schema: . rescript-stdlib-vendorer: 1.0.0 - rescript-struct: . ts-expect: 1.3.0 ts-node: 10.9.1 typescript: 4.9.3 @@ -24,8 +24,8 @@ importers: benchmark: 2.1.4 c8: 7.12.0 rescript: 11.0.0-rc.5 + rescript-schema: 'link:' rescript-stdlib-vendorer: 1.0.0 - rescript-struct: 'link:' ts-expect: 1.3.0 ts-node: 10.9.1_typescript@4.9.3 typescript: 4.9.3 diff --git a/src/S.bs.mjs b/src/S.bs.mjs index 835f12a2..13a91db3 100644 --- a/src/S.bs.mjs +++ b/src/S.bs.mjs @@ -1,130 +1,130 @@ // Generated by ReScript, PLEASE EDIT WITH CARE -import * as S_Core$RescriptStruct from "./S_Core.bs.mjs"; +import * as S_Core$RescriptSchema from "./S_Core.bs.mjs"; -var Literal = S_Core$RescriptStruct.Literal; +var Literal = S_Core$RescriptSchema.Literal; -var Path = S_Core$RescriptStruct.Path; +var Path = S_Core$RescriptSchema.Path; -var Raised = S_Core$RescriptStruct.Raised; +var Raised = S_Core$RescriptSchema.Raised; -var $$Error = S_Core$RescriptStruct.$$Error; +var $$Error = S_Core$RescriptSchema.$$Error; -var never = S_Core$RescriptStruct.never; +var never = S_Core$RescriptSchema.never; -var unknown = S_Core$RescriptStruct.unknown; +var unknown = S_Core$RescriptSchema.unknown; -var unit = S_Core$RescriptStruct.unit; +var unit = S_Core$RescriptSchema.unit; -var string = S_Core$RescriptStruct.string; +var string = S_Core$RescriptSchema.string; -var bool = S_Core$RescriptStruct.bool; +var bool = S_Core$RescriptSchema.bool; -var $$int = S_Core$RescriptStruct.$$int; +var $$int = S_Core$RescriptSchema.$$int; -var $$float = S_Core$RescriptStruct.$$float; +var $$float = S_Core$RescriptSchema.$$float; -var json = S_Core$RescriptStruct.json; +var json = S_Core$RescriptSchema.json; -var literal = S_Core$RescriptStruct.literal; +var literal = S_Core$RescriptSchema.literal; -var array = S_Core$RescriptStruct.array; +var array = S_Core$RescriptSchema.array; -var list = S_Core$RescriptStruct.list; +var list = S_Core$RescriptSchema.list; -var dict = S_Core$RescriptStruct.dict; +var dict = S_Core$RescriptSchema.dict; -var option = S_Core$RescriptStruct.option; +var option = S_Core$RescriptSchema.option; -var $$null = S_Core$RescriptStruct.$$null; +var $$null = S_Core$RescriptSchema.$$null; -var jsonString = S_Core$RescriptStruct.jsonString; +var jsonString = S_Core$RescriptSchema.jsonString; -var union = S_Core$RescriptStruct.union; +var union = S_Core$RescriptSchema.union; -var $$catch = S_Core$RescriptStruct.$$catch; +var $$catch = S_Core$RescriptSchema.$$catch; -var describe = S_Core$RescriptStruct.describe; +var describe = S_Core$RescriptSchema.describe; -var description = S_Core$RescriptStruct.description; +var description = S_Core$RescriptSchema.description; -var deprecate = S_Core$RescriptStruct.deprecate; +var deprecate = S_Core$RescriptSchema.deprecate; -var deprecation = S_Core$RescriptStruct.deprecation; +var deprecation = S_Core$RescriptSchema.deprecation; -var transform = S_Core$RescriptStruct.transform; +var transform = S_Core$RescriptSchema.transform; -var preprocess = S_Core$RescriptStruct.preprocess; +var preprocess = S_Core$RescriptSchema.preprocess; -var custom = S_Core$RescriptStruct.custom; +var custom = S_Core$RescriptSchema.custom; -var refine = S_Core$RescriptStruct.refine; +var refine = S_Core$RescriptSchema.refine; -var variant = S_Core$RescriptStruct.variant; +var variant = S_Core$RescriptSchema.variant; -var parseWith = S_Core$RescriptStruct.parseWith; +var parseWith = S_Core$RescriptSchema.parseWith; -var parseAnyWith = S_Core$RescriptStruct.parseAnyWith; +var parseAnyWith = S_Core$RescriptSchema.parseAnyWith; -var parseJsonStringWith = S_Core$RescriptStruct.parseJsonStringWith; +var parseJsonStringWith = S_Core$RescriptSchema.parseJsonStringWith; -var parseOrRaiseWith = S_Core$RescriptStruct.parseOrRaiseWith; +var parseOrRaiseWith = S_Core$RescriptSchema.parseOrRaiseWith; -var parseAnyOrRaiseWith = S_Core$RescriptStruct.parseAnyOrRaiseWith; +var parseAnyOrRaiseWith = S_Core$RescriptSchema.parseAnyOrRaiseWith; -var parseAsyncWith = S_Core$RescriptStruct.parseAsyncWith; +var parseAsyncWith = S_Core$RescriptSchema.parseAsyncWith; -var parseAnyAsyncWith = S_Core$RescriptStruct.parseAnyAsyncWith; +var parseAnyAsyncWith = S_Core$RescriptSchema.parseAnyAsyncWith; -var parseAsyncInStepsWith = S_Core$RescriptStruct.parseAsyncInStepsWith; +var parseAsyncInStepsWith = S_Core$RescriptSchema.parseAsyncInStepsWith; -var parseAnyAsyncInStepsWith = S_Core$RescriptStruct.parseAnyAsyncInStepsWith; +var parseAnyAsyncInStepsWith = S_Core$RescriptSchema.parseAnyAsyncInStepsWith; -var serializeWith = S_Core$RescriptStruct.serializeWith; +var serializeWith = S_Core$RescriptSchema.serializeWith; -var serializeToUnknownWith = S_Core$RescriptStruct.serializeToUnknownWith; +var serializeToUnknownWith = S_Core$RescriptSchema.serializeToUnknownWith; -var serializeToJsonStringWith = S_Core$RescriptStruct.serializeToJsonStringWith; +var serializeToJsonStringWith = S_Core$RescriptSchema.serializeToJsonStringWith; -var serializeOrRaiseWith = S_Core$RescriptStruct.serializeOrRaiseWith; +var serializeOrRaiseWith = S_Core$RescriptSchema.serializeOrRaiseWith; -var serializeToUnknownOrRaiseWith = S_Core$RescriptStruct.serializeToUnknownOrRaiseWith; +var serializeToUnknownOrRaiseWith = S_Core$RescriptSchema.serializeToUnknownOrRaiseWith; -var isAsyncParse = S_Core$RescriptStruct.isAsyncParse; +var isAsyncParse = S_Core$RescriptSchema.isAsyncParse; -var recursive = S_Core$RescriptStruct.recursive; +var recursive = S_Core$RescriptSchema.recursive; -var classify = S_Core$RescriptStruct.classify; +var classify = S_Core$RescriptSchema.classify; -var setName = S_Core$RescriptStruct.setName; +var setName = S_Core$RescriptSchema.setName; -var $$Object = S_Core$RescriptStruct.$$Object; +var $$Object = S_Core$RescriptSchema.$$Object; -var object = S_Core$RescriptStruct.object; +var object = S_Core$RescriptSchema.object; -var Tuple = S_Core$RescriptStruct.Tuple; +var Tuple = S_Core$RescriptSchema.Tuple; -var tuple = S_Core$RescriptStruct.tuple; +var tuple = S_Core$RescriptSchema.tuple; -var tuple1 = S_Core$RescriptStruct.tuple1; +var tuple1 = S_Core$RescriptSchema.tuple1; -var tuple2 = S_Core$RescriptStruct.tuple2; +var tuple2 = S_Core$RescriptSchema.tuple2; -var tuple3 = S_Core$RescriptStruct.tuple3; +var tuple3 = S_Core$RescriptSchema.tuple3; -var $$Option = S_Core$RescriptStruct.$$Option; +var $$Option = S_Core$RescriptSchema.$$Option; -var $$String = S_Core$RescriptStruct.$$String; +var $$String = S_Core$RescriptSchema.$$String; -var Int = S_Core$RescriptStruct.Int; +var Int = S_Core$RescriptSchema.Int; -var Float = S_Core$RescriptStruct.Float; +var Float = S_Core$RescriptSchema.Float; -var $$Array = S_Core$RescriptStruct.$$Array; +var $$Array = S_Core$RescriptSchema.$$Array; -var Metadata = S_Core$RescriptStruct.Metadata; +var Metadata = S_Core$RescriptSchema.Metadata; -var inline = S_Core$RescriptStruct.inline; +var inline = S_Core$RescriptSchema.inline; export { Literal , @@ -190,4 +190,4 @@ export { Metadata , inline , } -/* S_Core-RescriptStruct Not a pure module */ +/* S_Core-RescriptSchema Not a pure module */ diff --git a/src/S.d.ts b/src/S.d.ts index 8153237f..e166dcfa 100644 --- a/src/S.d.ts +++ b/src/S.d.ts @@ -1,4 +1,4 @@ -import { S_t, S_Error_class } from "../RescriptStruct.gen"; +import { S_t, S_Error_class } from "../RescriptSchema.gen"; export class Error extends S_Error_class { constructor( @@ -21,16 +21,16 @@ export type Result = | { success: false; error: Error }; export type EffectCtx = { - struct: Struct; + schema: Schema; fail: (message: string) => void; }; -export type Struct = S_t; +export type Schema = S_t; -export type Output = T extends Struct +export type Output = T extends Schema ? Output : never; -export type Input = T extends Struct ? Input : never; +export type Input = T extends Schema ? Input : never; export type Json = | string @@ -41,9 +41,9 @@ export type Json = | Json[]; type NoUndefined = T extends undefined ? never : T; -type UnknownStruct = Struct; -type StructTupleOutput< - Tuple extends UnknownStruct[], +type UnknownSchema = Schema; +type SchemaTupleOutput< + Tuple extends UnknownSchema[], Length extends number = Tuple["length"] > = Length extends Length ? number extends Length @@ -51,15 +51,15 @@ type StructTupleOutput< : _TupleOutput : never; type _TupleOutput< - Tuple extends UnknownStruct[], + Tuple extends UnknownSchema[], Length extends number, Accumulated extends unknown[], Index extends number = Accumulated["length"] > = Index extends Length ? Accumulated : _TupleOutput]>; -type StructTupleInput< - Tuple extends UnknownStruct[], +type SchemaTupleInput< + Tuple extends UnknownSchema[], Length extends number = Tuple["length"] > = Length extends Length ? number extends Length @@ -67,7 +67,7 @@ type StructTupleInput< : _TupleInput : never; type _TupleInput< - Tuple extends UnknownStruct[], + Tuple extends UnknownSchema[], Length extends number, Accumulated extends unknown[], Index extends number = Accumulated["length"] @@ -75,110 +75,110 @@ type _TupleInput< ? Accumulated : _TupleInput]>; -export const string: Struct; -export const boolean: Struct; -export const integer: Struct; -export const number: Struct; -export const never: Struct; -export const unknown: Struct; -export const json: Struct; -export const undefined: Struct; +export const string: Schema; +export const boolean: Schema; +export const integer: Schema; +export const number: Schema; +export const never: Schema; +export const unknown: Schema; +export const json: Schema; +export const undefined: Schema; export function literal( value: Literal -): Struct; +): Schema; export function literal( value: Literal -): Struct; +): Schema; export function literal( value: Literal -): Struct; +): Schema; export function literal( value: Literal -): Struct; +): Schema; export function literal( value: Literal -): Struct; -export function literal(value: undefined): Struct; -export function literal(value: null): Struct; -export function literal(value: T): Struct; +): Schema; +export function literal(value: undefined): Schema; +export function literal(value: null): Schema; +export function literal(value: T): Schema; -export function tuple(structs: []): Struct<[]>; +export function tuple(schemas: []): Schema<[]>; export function tuple( - structs: [Struct] -): Struct<[Output], [Input]>; -export function tuple( - structs: [A, ...B] -): Struct< - [Output, ...StructTupleOutput], - [Input, ...StructTupleInput] + schemas: [Schema] +): Schema<[Output], [Input]>; +export function tuple( + schemas: [A, ...B] +): Schema< + [Output, ...SchemaTupleOutput], + [Input, ...SchemaTupleInput] >; export function tuple( definer: (ctx: { item: ( inputIndex: InputIndex, - struct: Struct + schema: Schema ) => ItemOutput; tag: (inputIndex: number, value: unknown) => void; }) => Output -): Struct; +): Schema; export function optional( - struct: Struct -): Struct; + schema: Schema +): Schema; export function optional( - struct: Struct, + schema: Schema, or: () => Output -): Struct; +): Schema; export function optional( - struct: Struct, + schema: Schema, or: Output -): Struct; +): Schema; export const nullable: ( - struct: Struct -) => Struct; + schema: Schema +) => Schema; export const array: ( - struct: Struct -) => Struct; + schema: Schema +) => Schema; export const record: ( - struct: Struct -) => Struct, Record>; + schema: Schema +) => Schema, Record>; export const jsonString: ( - struct: Struct -) => Struct; + schema: Schema +) => Schema; -export const union: ( - structs: [A, ...B] -) => Struct< - Output | StructTupleOutput[number], - Input | StructTupleInput[number] +export const union: ( + schemas: [A, ...B] +) => Schema< + Output | SchemaTupleOutput[number], + Input | SchemaTupleInput[number] >; export function object( definer: (ctx: { field: ( inputFieldName: InputFieldName, - struct: Struct + schema: Schema ) => FieldOutput; fieldOr: ( name: InputFieldName, - struct: Struct, + schema: Schema, or: FieldOutput ) => FieldOutput; tag: (name: string, value: unknown) => void; }) => Output -): Struct; +): Schema; export function object< Shape extends { - [k in keyof Shape]: Struct; + [k in keyof Shape]: Schema; } >( shape: Shape -): Struct< +): Schema< { [k in keyof Shape]: Output; }, @@ -189,156 +189,156 @@ export function object< export const Object: { strip: ( - struct: Struct - ) => Struct; + schema: Schema + ) => Schema; strict: ( - struct: Struct - ) => Struct; + schema: Schema + ) => Schema; }; export function merge( - struct1: Struct>, - struct2: Struct> -): Struct>; + schema1: Schema>, + schema2: Schema> +): Schema>; export const String: { min: ( - struct: Struct, + schema: Schema, length: number, message?: string - ) => Struct; + ) => Schema; max: ( - struct: Struct, + schema: Schema, length: number, message?: string - ) => Struct; + ) => Schema; length: ( - struct: Struct, + schema: Schema, length: number, message?: string - ) => Struct; + ) => Schema; email: ( - struct: Struct, + schema: Schema, message?: string - ) => Struct; + ) => Schema; uuid: ( - struct: Struct, + schema: Schema, message?: string - ) => Struct; + ) => Schema; cuid: ( - struct: Struct, + schema: Schema, message?: string - ) => Struct; + ) => Schema; url: ( - struct: Struct, + schema: Schema, message?: string - ) => Struct; + ) => Schema; pattern: ( - struct: Struct, + schema: Schema, re: RegExp, message?: string - ) => Struct; + ) => Schema; datetime: ( - struct: Struct, + schema: Schema, message?: string - ) => Struct; - trim: (struct: Struct) => Struct; + ) => Schema; + trim: (schema: Schema) => Schema; }; export const Number: { min: ( - struct: Struct, + schema: Schema, value: number, message?: string - ) => Struct; + ) => Schema; max: ( - struct: Struct, + schema: Schema, value: number, message?: string - ) => Struct; + ) => Schema; }; export const Array: { - min: ( - struct: Struct, + min: ( + schema: Schema, length: number, message?: string - ) => Struct; - max: ( - struct: Struct, + ) => Schema; + max: ( + schema: Schema, length: number, message?: string - ) => Struct; - length: ( - struct: Struct, + ) => Schema; + length: ( + schema: Schema, length: number, message?: string - ) => Struct; + ) => Schema; }; export function custom( name: string, parser: (data: unknown, s: EffectCtx) => Output -): Struct; +): Schema; export function custom( name: string, parser: (data: unknown, s: EffectCtx) => Output | undefined, serializer: (value: Output, s: EffectCtx) => Input -): Struct; +): Schema; -export function name(struct: Struct): string; +export function name(schema: Schema): string; export function setName( - struct: Struct, + schema: Schema, name: string -): Struct; +): Schema; export function asyncParserRefine( - struct: Struct, + schema: Schema, refiner: (value: Output, s: EffectCtx) => Promise -): Struct; +): Schema; export function refine( - struct: Struct, + schema: Schema, refiner: (value: Output, s: EffectCtx) => void -): Struct; +): Schema; export function transform( - struct: Struct, + schema: Schema, parser: (value: Output, s: EffectCtx) => Transformed -): Struct; +): Schema; export function transform( - struct: Struct, + schema: Schema, parser: ( value: Output, s: EffectCtx ) => Transformed | undefined, serializer: (value: Transformed, s: EffectCtx) => Input -): Struct; +): Schema; export function describe( - struct: Struct, + schema: Schema, description: string -): Struct; +): Schema; export function description( - struct: Struct + schema: Schema ): string | undefined; export function parse( - struct: Struct, + schema: Schema, data: unknown ): Result; export function parseOrThrow( - struct: Struct, + schema: Schema, data: unknown ): Output; export function parseAsync( - struct: Struct, + schema: Schema, data: unknown ): Promise>; export function serialize( - struct: Struct, + schema: Schema, data: Output ): Result; export function serializeOrThrow( - struct: Struct, + schema: Schema, data: Output ): Input; diff --git a/src/S.resi b/src/S.resi index bc1ccd46..041499f4 100644 --- a/src/S.resi +++ b/src/S.resi @@ -60,18 +60,18 @@ and tagged = | Union(array>) | Dict(t) | JSON -and struct<'value> = t<'value> +and schema<'value> = t<'value> and error = private {operation: operation, code: errorCode, path: Path.t} and errorCode = | OperationFailed(string) | InvalidOperation({description: string}) - | InvalidType({expected: struct, received: unknown}) + | InvalidType({expected: schema, received: unknown}) | InvalidLiteral({expected: Literal.t, received: unknown}) | InvalidTupleSize({expected: int, received: int}) | ExcessField(string) | InvalidUnion(array) | UnexpectedAsync - | InvalidJsonStruct(struct) + | InvalidJsonStruct(schema) and operation = | Parsing | Serializing @@ -79,7 +79,7 @@ and unknownKeys = Strip | Strict type exn += private Raised(error) type effectCtx<'value> = { - struct: t<'value>, + schema: t<'value>, fail: 'a. (string, ~path: Path.t=?) => 'a, failWithError: 'a. error => 'a, } @@ -119,7 +119,7 @@ let union: array> => t<'value> type catchCtx<'value> = { @as("e") error: error, @as("i") input: unknown, - @as("s") struct: t<'value>, + @as("s") schema: t<'value>, @as("f") fail: 'a. (string, ~path: Path.t=?) => 'a, @as("w") failWithError: 'a. error => 'a, } diff --git a/src/S_Core.bs.mjs b/src/S_Core.bs.mjs index 05f4dd86..10467d00 100644 --- a/src/S_Core.bs.mjs +++ b/src/S_Core.bs.mjs @@ -209,11 +209,11 @@ function concat(path, concatedPath) { return path + concatedPath; } -var symbol = Symbol("rescript-struct"); +var symbol = Symbol("rescript-schema"); -var Raised = /* @__PURE__ */Caml_exceptions.create("S_Core-RescriptStruct.Raised"); +var Raised = /* @__PURE__ */Caml_exceptions.create("S_Core-RescriptSchema.Raised"); -class RescriptStructError extends Error { +class RescriptSchemaError extends Error { constructor(code, operation, path) { super(); this.operation = operation; @@ -223,7 +223,7 @@ class RescriptStructError extends Error { this.RE_EXN_ID = Raised; this._1 = this; this.Error = this; - this.name = "RescriptStructError"; + this.name = "RescriptSchemaError"; } get message() { return message(this); @@ -244,27 +244,27 @@ function getOrRethrow(exn) { function prependLocationOrRethrow(exn, $$location) { var error = getOrRethrow(exn); var path = "[" + JSON.stringify($$location) + "]" + error.path; - throw new RescriptStructError(error.code, error.operation, path); + throw new RescriptSchemaError(error.code, error.operation, path); } -function make(selfStruct, path, operation) { +function make(selfSchema, path, operation) { return { - struct: selfStruct, + schema: selfSchema, fail: (function (message, customPathOpt) { var customPath = customPathOpt !== undefined ? customPathOpt : ""; - throw new RescriptStructError({ + throw new RescriptSchemaError({ TAG: "OperationFailed", _0: message }, operation, path + customPath); }), failWithError: (function (error) { - throw new RescriptStructError(error.code, operation, path + error.path); + throw new RescriptSchemaError(error.code, operation, path + error.path); }) }; } -function classify$1(struct) { - return struct.t; +function classify$1(schema) { + return schema.t; } function scope(b, fn) { @@ -339,13 +339,13 @@ function embedAsyncOperation(b, input, fn) { function raiseWithArg(b, path, fn, arg) { return "e[" + (b.e.push(function (arg) { var code = fn(arg); - throw new RescriptStructError(code, b.o, path); + throw new RescriptSchemaError(code, b.o, path); }) - 1) + "](" + arg + ")"; } function fail(b, message, path) { return "e[" + (b.e.push(function () { - throw new RescriptStructError({ + throw new RescriptSchemaError({ TAG: "OperationFailed", _0: message }, b.o, path); @@ -353,7 +353,7 @@ function fail(b, message, path) { } function invalidOperation(b, path, description) { - throw new RescriptStructError({ + throw new RescriptSchemaError({ TAG: "InvalidOperation", description: description }, b.o, path); @@ -406,48 +406,48 @@ function withPathPrepend(b, path, maybeDynamicLocationVar, fn) { var error = Caml_js_exceptions.internalToOCamlException(raw_error); if (error.RE_EXN_ID === Raised) { var error$1 = error._1; - throw new RescriptStructError(error$1.code, error$1.operation, path + "[]" + error$1.path); + throw new RescriptSchemaError(error$1.code, error$1.operation, path + "[]" + error$1.path); } throw error; } } -function typeFilterCode(b, typeFilter, struct, inputVar, path) { +function typeFilterCode(b, typeFilter, schema, inputVar, path) { return "if(" + typeFilter(inputVar) + "){" + raiseWithArg(b, path, (function (input) { return { TAG: "InvalidType", - expected: struct, + expected: schema, received: input }; }), inputVar) + "}"; } -function use(b, struct, input, path) { +function use(b, schema, input, path) { var isParentAsync = b.a; var isParsing = b.o === "Parsing"; b.i = input; b.a = false; var output = ( - isParsing ? struct.p : struct.s - )(b, struct, path); + isParsing ? schema.p : schema.s + )(b, schema, path); if (isParsing) { - struct.i = b.a; + schema.i = b.a; b.a = isParentAsync || b.a; } return output; } -function useWithTypeFilter(b, struct, input, path) { - var typeFilter = struct.f; +function useWithTypeFilter(b, schema, input, path) { + var typeFilter = schema.f; var input$1; if (typeFilter !== undefined) { var inputVar = toVar(b, input); - b.c = b.c + typeFilterCode(b, typeFilter, struct, inputVar, path); + b.c = b.c + typeFilterCode(b, typeFilter, schema, inputVar, path); input$1 = inputVar; } else { input$1 = input; } - return use(b, struct, input$1, path); + return use(b, schema, input$1, path); } function noop(b, param, param$1) { @@ -458,7 +458,7 @@ function noopOperation(i) { return i; } -function build(builder, struct, operation) { +function build(builder, schema, operation) { var b = { a: false, c: "", @@ -469,13 +469,13 @@ function build(builder, struct, operation) { i: "i", e: [] }; - var output = builder(b, struct, ""); + var output = builder(b, schema, ""); if (operation === "Parsing") { - var typeFilter = struct.f; + var typeFilter = schema.f; if (typeFilter !== undefined) { - b.c = typeFilterCode(b, typeFilter, struct, "i", "") + b.c; + b.c = typeFilterCode(b, typeFilter, schema, "i", "") + b.c; } - struct.i = b.a; + schema.i = b.a; } if (b.c === "" && output === "i") { return noopOperation; @@ -486,10 +486,10 @@ function build(builder, struct, operation) { return new Function("e", "s", "return " + inlinedFunction)(b.e, symbol); } -function loop(_struct) { +function loop(_schema) { while(true) { - var struct = _struct; - var literal = struct.t; + var schema = _schema; + var literal = schema.t; if (typeof literal !== "object") { throw symbol; } @@ -509,7 +509,7 @@ function loop(_struct) { }) }; case "Union" : - _struct = literal._0[0]; + _schema = literal._0[0]; continue ; default: throw symbol; @@ -517,9 +517,9 @@ function loop(_struct) { }; } -function toLiteral(struct) { +function toLiteral(schema) { try { - return loop(struct); + return loop(schema); } catch (raw_jsExn){ var jsExn = Caml_js_exceptions.internalToOCamlException(raw_jsExn); @@ -534,14 +534,14 @@ function toLiteral(struct) { } } -function isAsyncParse(struct) { - var v = struct.i; +function isAsyncParse(schema) { + var v = schema.i; if (typeof v === "boolean") { return v; } try { - build(struct.p, struct, "Parsing"); - return struct.i; + build(schema.p, schema, "Parsing"); + return schema.i; } catch (raw_exn){ var exn = Caml_js_exceptions.internalToOCamlException(raw_exn); @@ -550,25 +550,25 @@ function isAsyncParse(struct) { } } -function validateJsonableStruct(_struct, rootStruct, _isRootOpt) { +function validateJsonableSchema(_schema, rootSchema, _isRootOpt) { while(true) { var isRootOpt = _isRootOpt; - var struct = _struct; + var schema = _schema; var isRoot = isRootOpt !== undefined ? isRootOpt : false; - if (!(isRoot || rootStruct !== struct)) { + if (!(isRoot || rootSchema !== schema)) { return ; } - var childrenStructs = struct.t; + var childrenSchemas = schema.t; var exit = 0; - if (typeof childrenStructs !== "object") { - if (childrenStructs !== "Unknown") { + if (typeof childrenSchemas !== "object") { + if (childrenSchemas !== "Unknown") { return ; } exit = 2; } else { - switch (childrenStructs.TAG) { + switch (childrenSchemas.TAG) { case "Literal" : - if (isJsonable(childrenStructs._0)) { + if (isJsonable(childrenSchemas._0)) { return ; } exit = 2; @@ -577,16 +577,16 @@ function validateJsonableStruct(_struct, rootStruct, _isRootOpt) { exit = 2; break; case "Object" : - var fieldNames = childrenStructs.fieldNames; - var fields = childrenStructs.fields; + var fieldNames = childrenSchemas.fieldNames; + var fields = childrenSchemas.fields; for(var idx = 0 ,idx_finish = fieldNames.length; idx < idx_finish; ++idx){ var fieldName = fieldNames[idx]; - var fieldStruct = fields[fieldName]; + var fieldSchema = fields[fieldName]; try { - var s = fieldStruct.t; + var s = fieldSchema.t; var tmp; - tmp = typeof s !== "object" || s.TAG !== "Option" ? fieldStruct : s._0; - validateJsonableStruct(tmp, rootStruct, undefined); + tmp = typeof s !== "object" || s.TAG !== "Option" ? fieldSchema : s._0; + validateJsonableSchema(tmp, rootSchema, undefined); } catch (raw_exn){ var exn = Caml_js_exceptions.internalToOCamlException(raw_exn); @@ -595,9 +595,9 @@ function validateJsonableStruct(_struct, rootStruct, _isRootOpt) { } return ; case "Tuple" : - childrenStructs._0.forEach(function (struct, i) { + childrenSchemas._0.forEach(function (schema, i) { try { - return validateJsonableStruct(struct, rootStruct, undefined); + return validateJsonableSchema(schema, rootSchema, undefined); } catch (raw_exn){ var exn = Caml_js_exceptions.internalToOCamlException(raw_exn); @@ -606,8 +606,8 @@ function validateJsonableStruct(_struct, rootStruct, _isRootOpt) { }); return ; case "Union" : - childrenStructs._0.forEach(function (struct) { - validateJsonableStruct(struct, rootStruct, undefined); + childrenSchemas._0.forEach(function (schema) { + validateJsonableSchema(schema, rootSchema, undefined); }); return ; case "Null" : @@ -621,12 +621,12 @@ function validateJsonableStruct(_struct, rootStruct, _isRootOpt) { switch (exit) { case 1 : _isRootOpt = undefined; - _struct = childrenStructs._0; + _schema = childrenSchemas._0; continue ; case 2 : - throw new RescriptStructError({ + throw new RescriptSchemaError({ TAG: "InvalidJsonStruct", - _0: struct + _0: schema }, "Serializing", ""); } @@ -634,12 +634,12 @@ function validateJsonableStruct(_struct, rootStruct, _isRootOpt) { } function unexpectedAsync(param) { - throw new RescriptStructError("UnexpectedAsync", "Parsing", ""); + throw new RescriptSchemaError("UnexpectedAsync", "Parsing", ""); } -function init(struct) { - var operation = build(struct.p, struct, "Parsing"); - var isAsync = struct.i; +function init(schema) { + var operation = build(schema.p, schema, "Parsing"); + var isAsync = schema.i; if (isAsync) { return unexpectedAsync; } else { @@ -661,11 +661,11 @@ function parseAnyOrRaiseWith(i, s) { } } -function parseAnyWith(any, struct) { +function parseAnyWith(any, schema) { try { return { TAG: "Ok", - _0: parseAnyOrRaiseWith(any, struct) + _0: parseAnyOrRaiseWith(any, schema) }; } catch (raw_exn){ @@ -691,9 +691,9 @@ function asyncPrepareError(jsExn) { }; } -function init$1(struct) { - var operation = build(struct.p, struct, "Parsing"); - var isAsync = struct.i; +function init$1(schema) { + var operation = build(schema.p, schema, "Parsing"); + var isAsync = schema.i; if (isAsync) { return operation; } else { @@ -720,9 +720,9 @@ function internalParseAsyncWith(i, s) { } } -function parseAnyAsyncWith(any, struct) { +function parseAnyAsyncWith(any, schema) { try { - return internalParseAsyncWith(any, struct)().then(asyncPrepareOk, asyncPrepareError); + return internalParseAsyncWith(any, schema)().then(asyncPrepareOk, asyncPrepareError); } catch (raw_exn){ var exn = Caml_js_exceptions.internalToOCamlException(raw_exn); @@ -733,9 +733,9 @@ function parseAnyAsyncWith(any, struct) { } } -function parseAnyAsyncInStepsWith(any, struct) { +function parseAnyAsyncInStepsWith(any, schema) { try { - var asyncFn = internalParseAsyncWith(any, struct); + var asyncFn = internalParseAsyncWith(any, schema); return { TAG: "Ok", _0: (function () { @@ -752,9 +752,9 @@ function parseAnyAsyncInStepsWith(any, struct) { } } -function init$2(struct) { - validateJsonableStruct(struct, struct, true); - return build(struct.s, struct, "Serializing"); +function init$2(schema) { + validateJsonableSchema(schema, schema, true); + return build(schema.s, schema, "Serializing"); } function serializeOrRaiseWith(i, s) { @@ -771,11 +771,11 @@ function serializeOrRaiseWith(i, s) { } } -function serializeWith(value, struct) { +function serializeWith(value, schema) { try { return { TAG: "Ok", - _0: serializeOrRaiseWith(value, struct) + _0: serializeOrRaiseWith(value, schema) }; } catch (raw_exn){ @@ -787,8 +787,8 @@ function serializeWith(value, struct) { } } -function init$3(struct) { - return build(struct.s, struct, "Serializing"); +function init$3(schema) { + return build(schema.s, schema, "Serializing"); } function serializeToUnknownOrRaiseWith(i, s) { @@ -805,11 +805,11 @@ function serializeToUnknownOrRaiseWith(i, s) { } } -function serializeToUnknownWith(value, struct) { +function serializeToUnknownWith(value, schema) { try { return { TAG: "Ok", - _0: serializeToUnknownOrRaiseWith(value, struct) + _0: serializeToUnknownOrRaiseWith(value, schema) }; } catch (raw_exn){ @@ -821,9 +821,9 @@ function serializeToUnknownWith(value, struct) { } } -function serializeToJsonStringWith(value, struct, spaceOpt) { +function serializeToJsonStringWith(value, schema, spaceOpt) { var space = spaceOpt !== undefined ? spaceOpt : 0; - var json = serializeWith(value, struct); + var json = serializeWith(value, schema); if (json.TAG === "Ok") { return { TAG: "Ok", @@ -834,7 +834,7 @@ function serializeToJsonStringWith(value, struct, spaceOpt) { } } -function parseJsonStringWith(json, struct) { +function parseJsonStringWith(json, schema) { var json$1; try { json$1 = { @@ -847,7 +847,7 @@ function parseJsonStringWith(json, struct) { if (error.RE_EXN_ID === Js_exn.$$Error) { json$1 = { TAG: "Error", - _0: new RescriptStructError({ + _0: new RescriptSchemaError({ TAG: "OperationFailed", _0: error._1.message }, "Parsing", "") @@ -857,7 +857,7 @@ function parseJsonStringWith(json, struct) { } } if (json$1.TAG === "Ok") { - return parseAnyWith(json$1._0, struct); + return parseAnyWith(json$1._0, schema); } else { return json$1; } @@ -882,18 +882,18 @@ function set(map, id, metadata) { return copy; } -function get(struct, id) { - return struct.m[id]; +function get(schema, id) { + return schema.m[id]; } -function set$1(struct, id, metadata) { - var metadataMap = set(struct.m, id, metadata); +function set$1(schema, id, metadata) { + var metadataMap = set(schema.m, id, metadata); return { - t: struct.t, - n: struct.n, - p: struct.p, - s: struct.s, - f: struct.f, + t: schema.t, + n: schema.n, + p: schema.p, + s: schema.s, + f: schema.f, i: 0, m: metadataMap }; @@ -903,12 +903,12 @@ function recursive(fn) { var placeholder = { m: empty }; - var struct = fn(placeholder); - Object.assign(placeholder, struct); + var schema = fn(placeholder); + Object.assign(placeholder, schema); var builder = placeholder.p; - placeholder.p = (function (b, selfStruct, path) { + placeholder.p = (function (b, selfSchema, path) { var input = b.i; - selfStruct.p = noop; + selfSchema.p = noop; var ctx = { a: false, c: "", @@ -919,27 +919,27 @@ function recursive(fn) { i: "i", e: [] }; - builder(ctx, selfStruct, path); + builder(ctx, selfSchema, path); var isAsync = ctx.a; - selfStruct.p = (function (b, selfStruct, param) { + selfSchema.p = (function (b, selfSchema, param) { var input = b.i; if (isAsync) { return embedAsyncOperation(b, input, (function (input) { - return internalParseAsyncWith(input, selfStruct); + return internalParseAsyncWith(input, selfSchema); })); } else { return embedSyncOperation(b, input, (function (input) { - return parseAnyOrRaiseWith(input, selfStruct); + return parseAnyOrRaiseWith(input, selfSchema); })); } }); - var operation = build(builder, selfStruct, "Parsing"); + var operation = build(builder, selfSchema, "Parsing"); if (isAsync) { - selfStruct["opa"] = operation; + selfSchema["opa"] = operation; } else { - selfStruct["op"] = operation; + selfSchema["op"] = operation; } - selfStruct.p = builder; + selfSchema.p = builder; return withPathPrepend(b, path, undefined, (function (b, param) { if (isAsync) { return embedAsyncOperation(b, input, operation); @@ -949,17 +949,17 @@ function recursive(fn) { })); }); var builder$1 = placeholder.s; - placeholder.s = (function (b, selfStruct, path) { + placeholder.s = (function (b, selfSchema, path) { var input = b.i; - selfStruct.s = (function (b, selfStruct, param) { + selfSchema.s = (function (b, selfSchema, param) { var input = b.i; return embedSyncOperation(b, input, (function (input) { - return serializeToUnknownOrRaiseWith(input, selfStruct); + return serializeToUnknownOrRaiseWith(input, selfSchema); })); }); - var operation = build(builder$1, selfStruct, "Serializing"); - selfStruct["os"] = operation; - selfStruct.s = builder$1; + var operation = build(builder$1, selfSchema, "Serializing"); + selfSchema["os"] = operation; + selfSchema.s = builder$1; return withPathPrepend(b, path, undefined, (function (b, param) { return embedSyncOperation(b, input, operation); })); @@ -967,17 +967,17 @@ function recursive(fn) { return placeholder; } -function setName(struct, name) { +function setName(schema, name) { return { - t: struct.t, + t: schema.t, n: (function () { return name; }), - p: struct.p, - s: struct.s, - f: struct.f, + p: schema.p, + s: schema.s, + f: schema.f, i: 0, - m: struct.m + m: schema.m }; } @@ -990,52 +990,52 @@ function containerName() { return tagged.TAG + "(" + tagged._0.n() + ")"; } -function internalRefine(struct, refiner) { +function internalRefine(schema, refiner) { return { - t: struct.t, - n: struct.n, - p: (function (b, selfStruct, path) { + t: schema.t, + n: schema.n, + p: (function (b, selfSchema, path) { var input = b.i; - return transform(b, use(b, struct, input, path), false, (function (b, input) { + return transform(b, use(b, schema, input, path), false, (function (b, input) { var inputVar = toVar(b, input); - b.c = b.c + refiner(b, inputVar, selfStruct, path); + b.c = b.c + refiner(b, inputVar, selfSchema, path); return inputVar; })); }), - s: (function (b, selfStruct, path) { + s: (function (b, selfSchema, path) { var input = b.i; - return use(b, struct, transform(b, input, false, (function (b, input) { + return use(b, schema, transform(b, input, false, (function (b, input) { var inputVar = toVar(b, input); - b.c = b.c + refiner(b, inputVar, selfStruct, path); + b.c = b.c + refiner(b, inputVar, selfSchema, path); return inputVar; })), path); }), - f: struct.f, + f: schema.f, i: 0, - m: struct.m + m: schema.m }; } -function refine(struct, refiner) { - return internalRefine(struct, (function (b, inputVar, selfStruct, path) { - var value = refiner(make(selfStruct, path, b.o)); +function refine(schema, refiner) { + return internalRefine(schema, (function (b, inputVar, selfSchema, path) { + var value = refiner(make(selfSchema, path, b.o)); return "e[" + (b.e.push(value) - 1) + "](" + inputVar + ");"; })); } -function addRefinement(struct, metadataId, refinement, refiner) { - var refinements = struct.m[metadataId]; - return internalRefine(set$1(struct, metadataId, refinements !== undefined ? refinements.concat(refinement) : [refinement]), refiner); +function addRefinement(schema, metadataId, refinement, refiner) { + var refinements = schema.m[metadataId]; + return internalRefine(set$1(schema, metadataId, refinements !== undefined ? refinements.concat(refinement) : [refinement]), refiner); } -function transform$1(struct, transformer) { +function transform$1(schema, transformer) { return { - t: struct.t, - n: struct.n, - p: (function (b, selfStruct, path) { + t: schema.t, + n: schema.n, + p: (function (b, selfSchema, path) { var input = b.i; - var input$1 = use(b, struct, input, path); - var match = transformer(make(selfStruct, path, b.o)); + var input$1 = use(b, schema, input, path); + var match = transformer(make(selfSchema, path, b.o)); var parser = match.p; if (parser !== undefined) { if (match.a !== undefined) { @@ -1053,48 +1053,48 @@ function transform$1(struct, transformer) { return input$1; } }), - s: (function (b, selfStruct, path) { + s: (function (b, selfSchema, path) { var input = b.i; - var match = transformer(make(selfStruct, path, b.o)); + var match = transformer(make(selfSchema, path, b.o)); var serializer = match.s; if (serializer !== undefined) { - return use(b, struct, embedSyncOperation(b, input, serializer), path); + return use(b, schema, embedSyncOperation(b, input, serializer), path); } else if (match.a !== undefined || match.p !== undefined) { return invalidOperation(b, path, "The S.transform serializer is missing"); } else { - return use(b, struct, input, path); + return use(b, schema, input, path); } }), - f: struct.f, + f: schema.f, i: 0, - m: struct.m + m: schema.m }; } -function preprocess(struct, transformer) { - var unionStructs = struct.t; - if (typeof unionStructs === "object" && unionStructs.TAG === "Union") { +function preprocess(schema, transformer) { + var unionSchemas = schema.t; + if (typeof unionSchemas === "object" && unionSchemas.TAG === "Union") { return { t: { TAG: "Union", - _0: unionStructs._0.map(function (unionStruct) { - return preprocess(unionStruct, transformer); + _0: unionSchemas._0.map(function (unionSchema) { + return preprocess(unionSchema, transformer); }) }, - n: struct.n, - p: struct.p, - s: struct.s, - f: struct.f, + n: schema.n, + p: schema.p, + s: schema.s, + f: schema.f, i: 0, - m: struct.m + m: schema.m }; } return { - t: struct.t, - n: struct.n, - p: (function (b, selfStruct, path) { + t: schema.t, + n: schema.n, + p: (function (b, selfSchema, path) { var input = b.i; - var match = transformer(make(selfStruct, path, b.o)); + var match = transformer(make(selfSchema, path, b.o)); var parser = match.p; if (parser !== undefined) { if (match.a !== undefined) { @@ -1102,28 +1102,28 @@ function preprocess(struct, transformer) { } var operationResultVar = $$var(b); b.c = b.c + (operationResultVar + "=" + embedSyncOperation(b, input, parser) + ";"); - return useWithTypeFilter(b, struct, operationResultVar, path); + return useWithTypeFilter(b, schema, operationResultVar, path); } var asyncParser = match.a; if (asyncParser === undefined) { - return useWithTypeFilter(b, struct, input, path); + return useWithTypeFilter(b, schema, input, path); } var parseResultVar = embedAsyncOperation(b, input, asyncParser); var outputVar = $$var(b); var asyncResultVar = varWithoutAllocation(b); b.c = b.c + (outputVar + "=()=>" + parseResultVar + "().then(" + asyncResultVar + "=>{" + scope(b, (function (b) { - var structOutputVar = useWithTypeFilter(b, struct, asyncResultVar, path); - var isAsync = struct.i; + var schemaOutputVar = useWithTypeFilter(b, schema, asyncResultVar, path); + var isAsync = schema.i; return "return " + ( - isAsync ? structOutputVar + "()" : structOutputVar + isAsync ? schemaOutputVar + "()" : schemaOutputVar ); })) + "});"); return outputVar; }), - s: (function (b, selfStruct, path) { + s: (function (b, selfSchema, path) { var input = b.i; - var input$1 = use(b, struct, input, path); - var match = transformer(make(selfStruct, path, b.o)); + var input$1 = use(b, schema, input, path); + var match = transformer(make(selfSchema, path, b.o)); var serializer = match.s; if (serializer !== undefined) { return embedSyncOperation(b, input$1, serializer); @@ -1133,7 +1133,7 @@ function preprocess(struct, transformer) { }), f: undefined, i: 0, - m: struct.m + m: schema.m }; } @@ -1143,9 +1143,9 @@ function custom(name, definer) { n: (function () { return name; }), - p: (function (b, selfStruct, path) { + p: (function (b, selfSchema, path) { var input = b.i; - var match = definer(make(selfStruct, path, b.o)); + var match = definer(make(selfSchema, path, b.o)); var parser = match.p; if (parser !== undefined) { if (match.a !== undefined) { @@ -1163,9 +1163,9 @@ function custom(name, definer) { return input; } }), - s: (function (b, selfStruct, path) { + s: (function (b, selfSchema, path) { var input = b.i; - var match = definer(make(selfStruct, path, b.o)); + var match = definer(make(selfSchema, path, b.o)); var serializer = match.s; if (serializer !== undefined) { return embedSyncOperation(b, input, serializer); @@ -1252,15 +1252,15 @@ function toKindWithSet(definition, embededSet) { } } -function factory(struct, definer) { +function factory(schema, definer) { return { - t: struct.t, - n: struct.n, + t: schema.t, + n: schema.n, p: (function (b, param, path) { var input = b.i; - return embedSyncOperation(b, use(b, struct, input, path), definer); + return embedSyncOperation(b, use(b, schema, input, path), definer); }), - s: (function (b, selfStruct, path) { + s: (function (b, selfSchema, path) { var inputVar = toVar(b, b.i); var definition = definer(symbol); var definitionToOutput = function (definition, outputPath) { @@ -1304,39 +1304,39 @@ function factory(struct, definer) { }; var output = definitionToOutput(definition, ""); if (typeof output === "string") { - return use(b, struct, output, path); + return use(b, schema, output, path); } if (output !== 0) { return invalidOperation(b, path, "Can't create serializer. The S.variant's value is registered multiple times. Use S.transform instead"); } - var literal = toLiteral(selfStruct); + var literal = toLiteral(selfSchema); if (literal === undefined) { return invalidOperation(b, path, "Can't create serializer. The S.variant's value is not registered and not a literal. Use S.transform instead"); } var value$1 = value(literal); - return use(b, struct, "e[" + (b.e.push(value$1) - 1) + "]", path); + return use(b, schema, "e[" + (b.e.push(value$1) - 1) + "]", path); }), - f: struct.f, + f: schema.f, i: 0, - m: struct.m + m: schema.m }; } -var defaultMetadataId = "rescript-struct:Option.default"; +var defaultMetadataId = "rescript-schema:Option.default"; -function $$default(struct) { - return struct.m[defaultMetadataId]; +function $$default(schema) { + return schema.m[defaultMetadataId]; } -function parseOperationBuilder(b, selfStruct, path) { +function parseOperationBuilder(b, selfSchema, path) { var inputVar = toVar(b, b.i); var outputVar = $$var(b); - var isNull = (selfStruct.t.TAG === "Null"); - var childStruct = selfStruct.t._0; + var isNull = (selfSchema.t.TAG === "Null"); + var childSchema = selfSchema.t._0; var ifCode = scope(b, (function (b) { - return outputVar + "=" + use(b, childStruct, inputVar, path); + return outputVar + "=" + use(b, childSchema, inputVar, path); })); - var isAsync = childStruct.i; + var isAsync = childSchema.i; b.c = b.c + ("if(" + inputVar + "!==" + ( isNull ? "null" : "void 0" ) + "){" + ifCode + "}else{" + outputVar + "=" + ( @@ -1345,22 +1345,22 @@ function parseOperationBuilder(b, selfStruct, path) { return outputVar; } -function serializeOperationBuilder(b, selfStruct, path) { +function serializeOperationBuilder(b, selfSchema, path) { var inputVar = toVar(b, b.i); var outputVar = $$var(b); - var isNull = (selfStruct.t.TAG === "Null"); - var childStruct = selfStruct.t._0; + var isNull = (selfSchema.t.TAG === "Null"); + var childSchema = selfSchema.t._0; b.c = b.c + ("if(" + inputVar + "!==void 0){" + scope(b, (function (b) { var value = Caml_option.valFromOption; - return outputVar + "=" + use(b, childStruct, "e[" + (b.e.push(value) - 1) + "](" + inputVar + ")", path); + return outputVar + "=" + use(b, childSchema, "e[" + (b.e.push(value) - 1) + "](" + inputVar + ")", path); })) + "}else{" + outputVar + "=" + ( isNull ? "null" : "void 0" ) + "}"); return outputVar; } -function maybeTypeFilter(struct, inlinedNoneValue) { - var typeFilter = struct.f; +function maybeTypeFilter(schema, inlinedNoneValue) { + var typeFilter = schema.f; if (typeFilter !== undefined) { return (function (inputVar) { return inputVar + "!==" + inlinedNoneValue + "&&(" + typeFilter(inputVar) + ")"; @@ -1369,64 +1369,64 @@ function maybeTypeFilter(struct, inlinedNoneValue) { } -function factory$1(struct) { +function factory$1(schema) { return { t: { TAG: "Option", - _0: struct + _0: schema }, n: containerName, p: parseOperationBuilder, s: serializeOperationBuilder, - f: maybeTypeFilter(struct, "void 0"), + f: maybeTypeFilter(schema, "void 0"), i: 0, m: empty }; } -function getWithDefault(struct, $$default) { +function getWithDefault(schema, $$default) { return { - t: struct.t, - n: struct.n, + t: schema.t, + n: schema.n, p: (function (b, param, path) { var input = b.i; - return transform(b, use(b, struct, input, path), false, (function (b, input) { + return transform(b, use(b, schema, input, path), false, (function (b, input) { var tmp; tmp = $$default.TAG === "Value" ? "e[" + (b.e.push($$default._0) - 1) + "]" : "e[" + (b.e.push($$default._0) - 1) + "]()"; return input + "===void 0?" + tmp + ":" + input; })); }), - s: struct.s, - f: struct.f, + s: schema.s, + f: schema.f, i: 0, - m: set(struct.m, defaultMetadataId, $$default) + m: set(schema.m, defaultMetadataId, $$default) }; } -function getOr(struct, defalutValue) { - return getWithDefault(struct, { +function getOr(schema, defalutValue) { + return getWithDefault(schema, { TAG: "Value", _0: defalutValue }); } -function getOrWith(struct, defalutCb) { - return getWithDefault(struct, { +function getOrWith(schema, defalutCb) { + return getWithDefault(schema, { TAG: "Callback", _0: defalutCb }); } -function factory$2(struct) { +function factory$2(schema) { return { t: { TAG: "Null", - _0: struct + _0: schema }, n: containerName, p: parseOperationBuilder, s: serializeOperationBuilder, - f: maybeTypeFilter(struct, "null"), + f: maybeTypeFilter(schema, "null"), i: 0, m: empty }; @@ -1441,14 +1441,14 @@ function noopRefinement(_b, param, param$1, param$2) { } function makeParseOperationBuilder(itemDefinitions, itemDefinitionsSet, definition, inputRefinement, unknownKeysRefinement) { - return function (b, selfStruct, path) { + return function (b, selfSchema, path) { var inputVar = toVar(b, b.i); var registeredDefinitions = new Set(); var asyncOutputVars = []; - inputRefinement(b, selfStruct, inputVar, path); + inputRefinement(b, selfSchema, inputVar, path); var prevCode = b.c; b.c = ""; - unknownKeysRefinement(b, selfStruct, inputVar, path); + unknownKeysRefinement(b, selfSchema, inputVar, path); var unknownKeysRefinementCode = b.c; b.c = ""; var definitionToOutput = function (definition, outputPath) { @@ -1474,9 +1474,9 @@ function makeParseOperationBuilder(itemDefinitions, itemDefinitionsSet, definiti case 2 : registeredDefinitions.add(definition); var inputPath = definition.p; - var struct = definition.s; - var fieldOuputVar = useWithTypeFilter(b, struct, inputVar + inputPath, path + inputPath); - var isAsyncField = struct.i; + var schema = definition.s; + var fieldOuputVar = useWithTypeFilter(b, schema, inputVar + inputPath, path + inputPath); + var isAsyncField = schema.i; if (isAsyncField) { asyncOutputVars.push(fieldOuputVar); } @@ -1491,9 +1491,9 @@ function makeParseOperationBuilder(itemDefinitions, itemDefinitionsSet, definiti var itemDefinition = itemDefinitions[idx]; if (!registeredDefinitions.has(itemDefinition)) { var inputPath = itemDefinition.p; - var struct = itemDefinition.s; - var fieldOuputVar = useWithTypeFilter(b, struct, inputVar + inputPath, path + inputPath); - var isAsyncField = struct.i; + var schema = itemDefinition.s; + var fieldOuputVar = useWithTypeFilter(b, schema, inputVar + inputPath, path + inputPath); + var isAsyncField = schema.i; if (isAsyncField) { asyncOutputVars.push(fieldOuputVar); } @@ -1518,18 +1518,18 @@ function factory$3(definer) { var fields = {}; var fieldNames = []; var itemDefinitionsSet = new Set(); - var field = function (fieldName, struct) { + var field = function (fieldName, schema) { var inlinedInputLocation = JSON.stringify(fieldName); if (fields[fieldName]) { - throw new Error("[rescript-struct] " + ("The field " + inlinedInputLocation + " is defined multiple times. If you want to duplicate the field, use S.transform instead.")); + throw new Error("[rescript-schema] " + ("The field " + inlinedInputLocation + " is defined multiple times. If you want to duplicate the field, use S.transform instead.")); } var itemDefinition_p = "[" + inlinedInputLocation + "]"; var itemDefinition = { - s: struct, + s: schema, l: inlinedInputLocation, p: itemDefinition_p }; - fields[fieldName] = struct; + fields[fieldName] = schema; fieldNames.push(fieldName); itemDefinitionsSet.add(itemDefinition); return itemDefinition; @@ -1537,8 +1537,8 @@ function factory$3(definer) { var tag = function (tag$1, asValue) { field(tag$1, literal(asValue)); }; - var fieldOr = function (fieldName, struct, or) { - return field(fieldName, getOr(factory$1(struct), or)); + var fieldOr = function (fieldName, schema, or) { + return field(fieldName, getOr(factory$1(schema), or)); }; var ctx = { n: fieldNames, @@ -1565,12 +1565,12 @@ function factory$3(definer) { }, n: (function () { return "Object({" + fieldNames$1.map(function (fieldName) { - var fieldStruct = fields$1[fieldName]; - return JSON.stringify(fieldName) + ": " + fieldStruct.n(); + var fieldSchema = fields$1[fieldName]; + return JSON.stringify(fieldName) + ": " + fieldSchema.n(); }).join(", ") + "})"; }), - p: makeParseOperationBuilder(itemDefinitions, itemDefinitionsSet$1, definition, noopRefinement, (function (b, selfStruct, inputVar, path) { - var withUnknownKeysRefinement = selfStruct.t.unknownKeys === "Strict"; + p: makeParseOperationBuilder(itemDefinitions, itemDefinitionsSet$1, definition, noopRefinement, (function (b, selfSchema, inputVar, path) { + var withUnknownKeysRefinement = selfSchema.t.unknownKeys === "Strict"; if (!withUnknownKeysRefinement) { return ; } @@ -1663,10 +1663,10 @@ function factory$3(definer) { }; } -function strip(struct) { - var match = struct.t; +function strip(schema) { + var match = schema.t; if (typeof match !== "object" || !(match.TAG === "Object" && match.unknownKeys !== "Strip")) { - return struct; + return schema; } else { return { t: { @@ -1675,20 +1675,20 @@ function strip(struct) { fieldNames: match.fieldNames, unknownKeys: "Strip" }, - n: struct.n, - p: struct.p, - s: struct.s, - f: struct.f, + n: schema.n, + p: schema.p, + s: schema.s, + f: schema.f, i: 0, - m: struct.m + m: schema.m }; } } -function strict(struct) { - var match = struct.t; +function strict(schema) { + var match = schema.t; if (typeof match !== "object" || !(match.TAG === "Object" && match.unknownKeys === "Strip")) { - return struct; + return schema; } else { return { t: { @@ -1697,29 +1697,29 @@ function strict(struct) { fieldNames: match.fieldNames, unknownKeys: "Strict" }, - n: struct.n, - p: struct.p, - s: struct.s, - f: struct.f, + n: schema.n, + p: schema.p, + s: schema.s, + f: schema.f, i: 0, - m: struct.m + m: schema.m }; } } -function builder(b, selfStruct, path) { +function builder(b, selfSchema, path) { var input = b.i; b.c = b.c + raiseWithArg(b, path, (function (input) { return { TAG: "InvalidType", - expected: selfStruct, + expected: selfSchema, received: input }; }), input) + ";"; return input; } -var struct = { +var schema = { t: "Never", n: primitiveName, p: builder, @@ -1729,7 +1729,7 @@ var struct = { m: empty }; -var struct$1 = { +var schema$1 = { t: "Unknown", n: primitiveName, p: noop, @@ -1739,10 +1739,10 @@ var struct$1 = { m: empty }; -var metadataId = "rescript-struct:String.refinements"; +var metadataId = "rescript-schema:String.refinements"; -function refinements(struct) { - var m = struct.m[metadataId]; +function refinements(schema) { + var m = schema.m[metadataId]; if (m !== undefined) { return m; } else { @@ -1762,7 +1762,7 @@ function typeFilter$1(inputVar) { return "typeof " + inputVar + "!==\"string\""; } -var struct$2 = { +var schema$2 = { t: "String", n: primitiveName, p: noop, @@ -1772,9 +1772,9 @@ var struct$2 = { m: empty }; -function min(struct, length, maybeMessage) { +function min(schema, length, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "String must be " + length + " or more characters long"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: { TAG: "Min", length: length @@ -1785,9 +1785,9 @@ function min(struct, length, maybeMessage) { })); } -function max(struct, length, maybeMessage) { +function max(schema, length, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "String must be " + length + " or fewer characters long"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: { TAG: "Max", length: length @@ -1798,9 +1798,9 @@ function max(struct, length, maybeMessage) { })); } -function length(struct, length$1, maybeMessage) { +function length(schema, length$1, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "String must be exactly " + length$1 + " characters long"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: { TAG: "Length", length: length$1 @@ -1811,9 +1811,9 @@ function length(struct, length$1, maybeMessage) { })); } -function email(struct, messageOpt) { +function email(schema, messageOpt) { var message = messageOpt !== undefined ? messageOpt : "Invalid email address"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: "Email", message: message }, (function (b, inputVar, param, path) { @@ -1821,9 +1821,9 @@ function email(struct, messageOpt) { })); } -function uuid(struct, messageOpt) { +function uuid(schema, messageOpt) { var message = messageOpt !== undefined ? messageOpt : "Invalid UUID"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: "Uuid", message: message }, (function (b, inputVar, param, path) { @@ -1831,9 +1831,9 @@ function uuid(struct, messageOpt) { })); } -function cuid(struct, messageOpt) { +function cuid(schema, messageOpt) { var message = messageOpt !== undefined ? messageOpt : "Invalid CUID"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: "Cuid", message: message }, (function (b, inputVar, param, path) { @@ -1841,9 +1841,9 @@ function cuid(struct, messageOpt) { })); } -function url(struct, messageOpt) { +function url(schema, messageOpt) { var message = messageOpt !== undefined ? messageOpt : "Invalid url"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: "Url", message: message }, (function (b, inputVar, param, path) { @@ -1851,9 +1851,9 @@ function url(struct, messageOpt) { })); } -function pattern(struct, re, messageOpt) { +function pattern(schema, re, messageOpt) { var message = messageOpt !== undefined ? messageOpt : "Invalid"; - return addRefinement(struct, metadataId, { + return addRefinement(schema, metadataId, { kind: { TAG: "Pattern", re: re @@ -1865,14 +1865,14 @@ function pattern(struct, re, messageOpt) { })); } -function datetime(struct, messageOpt) { +function datetime(schema, messageOpt) { var message = messageOpt !== undefined ? messageOpt : "Invalid datetime string! Must be UTC"; var refinement = { kind: "Datetime", message: message }; - var refinements = struct.m[metadataId]; - return transform$1(set$1(struct, metadataId, refinements !== undefined ? refinements.concat(refinement) : [refinement]), (function (s) { + var refinements = schema.m[metadataId]; + return transform$1(set$1(schema, metadataId, refinements !== undefined ? refinements.concat(refinement) : [refinement]), (function (s) { return { p: (function (string) { if (!datetimeRe.test(string)) { @@ -1887,11 +1887,11 @@ function datetime(struct, messageOpt) { })); } -function trim(struct) { +function trim(schema) { var transformer = function (string) { return string.trim(); }; - return transform$1(struct, (function (param) { + return transform$1(schema, (function (param) { return { p: transformer, s: transformer @@ -1899,15 +1899,15 @@ function trim(struct) { })); } -function factory$4(struct) { +function factory$4(schema) { try { - validateJsonableStruct(struct, struct, true); + validateJsonableSchema(schema, schema, true); } catch (raw_exn){ var exn = Caml_js_exceptions.internalToOCamlException(raw_exn); getOrRethrow(exn); - var message = "The struct " + struct.n() + " passed to S.jsonString is not compatible with JSON"; - throw new Error("[rescript-struct] " + message); + var message = "The schema " + schema.n() + " passed to S.jsonString is not compatible with JSON"; + throw new Error("[rescript-schema] " + message); } return { t: "String", @@ -1921,11 +1921,11 @@ function factory$4(struct) { _0: message }; }), "t.message") + "}"); - return useWithTypeFilter(b, struct, jsonVar, path); + return useWithTypeFilter(b, schema, jsonVar, path); }), s: (function (b, param, path) { var input = b.i; - return "JSON.stringify(" + use(b, struct, input, path) + ")"; + return "JSON.stringify(" + use(b, schema, input, path) + ")"; }), f: typeFilter$1, i: 0, @@ -1937,7 +1937,7 @@ function typeFilter$2(inputVar) { return "typeof " + inputVar + "!==\"boolean\""; } -var struct$3 = { +var schema$3 = { t: "Bool", n: primitiveName, p: noop, @@ -1947,10 +1947,10 @@ var struct$3 = { m: empty }; -var metadataId$1 = "rescript-struct:Int.refinements"; +var metadataId$1 = "rescript-schema:Int.refinements"; -function refinements$1(struct) { - var m = struct.m[metadataId$1]; +function refinements$1(schema) { + var m = schema.m[metadataId$1]; if (m !== undefined) { return m; } else { @@ -1962,7 +1962,7 @@ function typeFilter$3(inputVar) { return "typeof " + inputVar + "!==\"number\"||" + inputVar + ">2147483647||" + inputVar + "<-2147483648||" + inputVar + "%1!==0"; } -var struct$4 = { +var schema$4 = { t: "Int", n: primitiveName, p: noop, @@ -1972,9 +1972,9 @@ var struct$4 = { m: empty }; -function min$1(struct, minValue, maybeMessage) { +function min$1(schema, minValue, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "Number must be greater than or equal to " + minValue; - return addRefinement(struct, metadataId$1, { + return addRefinement(schema, metadataId$1, { kind: { TAG: "Min", value: minValue @@ -1985,9 +1985,9 @@ function min$1(struct, minValue, maybeMessage) { })); } -function max$1(struct, maxValue, maybeMessage) { +function max$1(schema, maxValue, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "Number must be lower than or equal to " + maxValue; - return addRefinement(struct, metadataId$1, { + return addRefinement(schema, metadataId$1, { kind: { TAG: "Max", value: maxValue @@ -1998,9 +1998,9 @@ function max$1(struct, maxValue, maybeMessage) { })); } -function port(struct, messageOpt) { +function port(schema, messageOpt) { var message = messageOpt !== undefined ? messageOpt : "Invalid port"; - return addRefinement(struct, metadataId$1, { + return addRefinement(schema, metadataId$1, { kind: "Port", message: message }, (function (b, inputVar, param, path) { @@ -2008,10 +2008,10 @@ function port(struct, messageOpt) { })); } -var metadataId$2 = "rescript-struct:Float.refinements"; +var metadataId$2 = "rescript-schema:Float.refinements"; -function refinements$2(struct) { - var m = struct.m[metadataId$2]; +function refinements$2(schema) { + var m = schema.m[metadataId$2]; if (m !== undefined) { return m; } else { @@ -2023,7 +2023,7 @@ function typeFilter$4(inputVar) { return "typeof " + inputVar + "!==\"number\"||Number.isNaN(" + inputVar + ")"; } -var struct$5 = { +var schema$5 = { t: "Float", n: primitiveName, p: noop, @@ -2033,9 +2033,9 @@ var struct$5 = { m: empty }; -function min$2(struct, minValue, maybeMessage) { +function min$2(schema, minValue, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "Number must be greater than or equal to " + minValue; - return addRefinement(struct, metadataId$2, { + return addRefinement(schema, metadataId$2, { kind: { TAG: "Min", value: minValue @@ -2046,9 +2046,9 @@ function min$2(struct, minValue, maybeMessage) { })); } -function max$2(struct, maxValue, maybeMessage) { +function max$2(schema, maxValue, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "Number must be lower than or equal to " + maxValue; - return addRefinement(struct, metadataId$2, { + return addRefinement(schema, metadataId$2, { kind: { TAG: "Max", value: maxValue @@ -2059,10 +2059,10 @@ function max$2(struct, maxValue, maybeMessage) { })); } -var metadataId$3 = "rescript-struct:Array.refinements"; +var metadataId$3 = "rescript-schema:Array.refinements"; -function refinements$3(struct) { - var m = struct.m[metadataId$3]; +function refinements$3(schema) { + var m = schema.m[metadataId$3]; if (m !== undefined) { return m; } else { @@ -2074,11 +2074,11 @@ function typeFilter$5(inputVar) { return "!Array.isArray(" + inputVar + ")"; } -function factory$5(struct) { +function factory$5(schema) { return { t: { TAG: "Array", - _0: struct + _0: schema }, n: containerName, p: (function (b, param, path) { @@ -2087,11 +2087,11 @@ function factory$5(struct) { var outputVar = $$var(b); b.c = b.c + (outputVar + "=[];for(let " + iteratorVar + "=0;" + iteratorVar + "<" + inputVar + ".length;++" + iteratorVar + "){" + scope(b, (function (b) { var itemOutputVar = withPathPrepend(b, path, iteratorVar, (function (b, path) { - return useWithTypeFilter(b, struct, inputVar + "[" + iteratorVar + "]", path); + return useWithTypeFilter(b, schema, inputVar + "[" + iteratorVar + "]", path); })); return outputVar + ".push(" + itemOutputVar + ")"; })) + "}"); - var isAsync = struct.i; + var isAsync = schema.i; if (!isAsync) { return outputVar; } @@ -2100,7 +2100,7 @@ function factory$5(struct) { return asyncOutputVar; }), s: (function (b, param, path) { - if (struct.s === noop) { + if (schema.s === noop) { return b.i; } var inputVar = toVar(b, b.i); @@ -2108,7 +2108,7 @@ function factory$5(struct) { var outputVar = $$var(b); b.c = b.c + (outputVar + "=[];for(let " + iteratorVar + "=0;" + iteratorVar + "<" + inputVar + ".length;++" + iteratorVar + "){" + scope(b, (function (b) { var itemOutputVar = withPathPrepend(b, path, iteratorVar, (function (b, path) { - return use(b, struct, inputVar + "[" + iteratorVar + "]", path); + return use(b, schema, inputVar + "[" + iteratorVar + "]", path); })); return outputVar + ".push(" + itemOutputVar + ")"; })) + "}"); @@ -2120,9 +2120,9 @@ function factory$5(struct) { }; } -function min$3(struct, length, maybeMessage) { +function min$3(schema, length, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "Array must be " + length + " or more items long"; - return addRefinement(struct, metadataId$3, { + return addRefinement(schema, metadataId$3, { kind: { TAG: "Min", length: length @@ -2133,9 +2133,9 @@ function min$3(struct, length, maybeMessage) { })); } -function max$3(struct, length, maybeMessage) { +function max$3(schema, length, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "Array must be " + length + " or fewer items long"; - return addRefinement(struct, metadataId$3, { + return addRefinement(schema, metadataId$3, { kind: { TAG: "Max", length: length @@ -2146,9 +2146,9 @@ function max$3(struct, length, maybeMessage) { })); } -function length$1(struct, length$2, maybeMessage) { +function length$1(schema, length$2, maybeMessage) { var message = maybeMessage !== undefined ? maybeMessage : "Array must be exactly " + length$2 + " items long"; - return addRefinement(struct, metadataId$3, { + return addRefinement(schema, metadataId$3, { kind: { TAG: "Length", length: length$2 @@ -2159,11 +2159,11 @@ function length$1(struct, length$2, maybeMessage) { })); } -function factory$6(struct) { +function factory$6(schema) { return { t: { TAG: "Dict", - _0: struct + _0: schema }, n: containerName, p: (function (b, param, path) { @@ -2172,11 +2172,11 @@ function factory$6(struct) { var outputVar = $$var(b); b.c = b.c + (outputVar + "={};for(let " + keyVar + " in " + inputVar + "){" + scope(b, (function (b) { var itemOutputVar = withPathPrepend(b, path, keyVar, (function (b, path) { - return useWithTypeFilter(b, struct, inputVar + "[" + keyVar + "]", path); + return useWithTypeFilter(b, schema, inputVar + "[" + keyVar + "]", path); })); return outputVar + "[" + keyVar + "]=" + itemOutputVar; })) + "}"); - var isAsync = struct.i; + var isAsync = schema.i; if (!isAsync) { return outputVar; } @@ -2189,7 +2189,7 @@ function factory$6(struct) { return asyncOutputVar; }), s: (function (b, param, path) { - if (struct.s === noop) { + if (schema.s === noop) { return b.i; } var inputVar = toVar(b, b.i); @@ -2197,7 +2197,7 @@ function factory$6(struct) { var outputVar = $$var(b); b.c = b.c + (outputVar + "={};for(let " + keyVar + " in " + inputVar + "){" + scope(b, (function (b) { var itemOutputVar = withPathPrepend(b, path, keyVar, (function (b, path) { - return use(b, struct, inputVar + "[" + keyVar + "]", path); + return use(b, schema, inputVar + "[" + keyVar + "]", path); })); return outputVar + "[" + keyVar + "]=" + itemOutputVar; })) + "}"); @@ -2210,20 +2210,20 @@ function factory$6(struct) { } function factory$7(definer) { - var structs = []; + var schemas = []; var itemDefinitionsSet = new Set(); - var item = function (idx, struct) { + var item = function (idx, schema) { var inlinedInputLocation = "\"" + idx + "\""; - if (structs[idx]) { - throw new Error("[rescript-struct] " + ("The item " + inlinedInputLocation + " is defined multiple times. If you want to duplicate the item, use S.transform instead.")); + if (schemas[idx]) { + throw new Error("[rescript-schema] " + ("The item " + inlinedInputLocation + " is defined multiple times. If you want to duplicate the item, use S.transform instead.")); } var itemDefinition_p = "[" + inlinedInputLocation + "]"; var itemDefinition = { - s: struct, + s: schema, l: inlinedInputLocation, p: itemDefinition_p }; - structs[idx] = struct; + schemas[idx] = schema; itemDefinitionsSet.add(itemDefinition); return itemDefinition; }; @@ -2231,7 +2231,7 @@ function factory$7(definer) { item(idx, literal(asValue)); }; var ctx = { - s: structs, + s: schemas, d: itemDefinitionsSet, item: item, tag: tag, @@ -2240,10 +2240,10 @@ function factory$7(definer) { }; var definition = definer(ctx); var itemDefinitionsSet$1 = itemDefinitionsSet; - var structs$1 = structs; - var length = structs$1.length; + var schemas$1 = schemas; + var length = schemas$1.length; for(var idx = 0; idx < length; ++idx){ - if (!structs$1[idx]) { + if (!schemas$1[idx]) { var inlinedInputLocation = "\"" + idx + "\""; var itemDefinition_p = "[" + inlinedInputLocation + "]"; var itemDefinition = { @@ -2251,7 +2251,7 @@ function factory$7(definer) { l: inlinedInputLocation, p: itemDefinition_p }; - structs$1[idx] = unit; + schemas$1[idx] = unit; itemDefinitionsSet$1.add(itemDefinition); } @@ -2260,10 +2260,10 @@ function factory$7(definer) { return { t: { TAG: "Tuple", - _0: structs$1 + _0: schemas$1 }, n: (function () { - return "Tuple(" + structs$1.map(function (s) { + return "Tuple(" + schemas$1.map(function (s) { return s.n(); }).join(", ") + ")"; }), @@ -2337,32 +2337,32 @@ function factory$7(definer) { }; } -function factory$8(structs) { - if (structs.length < 2) { - throw new Error("[rescript-struct] A Union struct factory require at least two structs."); +function factory$8(schemas) { + if (schemas.length < 2) { + throw new Error("[rescript-schema] A Union schema factory require at least two schemas."); } return { t: { TAG: "Union", - _0: structs + _0: schemas }, n: (function () { - return "Union(" + structs.map(function (s) { + return "Union(" + schemas.map(function (s) { return s.n(); }).join(", ") + ")"; }), - p: (function (b, selfStruct, path) { + p: (function (b, selfSchema, path) { var inputVar = toVar(b, b.i); - var structs = selfStruct.t._0; + var schemas = selfSchema.t._0; var isAsyncRef = false; var itemsCode = []; var itemsOutputVar = []; var prevCode = b.c; - for(var idx = 0 ,idx_finish = structs.length; idx < idx_finish; ++idx){ - var struct = structs[idx]; + for(var idx = 0 ,idx_finish = schemas.length; idx < idx_finish; ++idx){ + var schema = schemas[idx]; b.c = ""; - var itemOutputVar = useWithTypeFilter(b, struct, inputVar, ""); - var isAsyncItem = struct.i; + var itemOutputVar = useWithTypeFilter(b, schema, inputVar, ""); + var isAsyncItem = schema.i; if (isAsyncItem) { isAsyncRef = true; } @@ -2374,11 +2374,11 @@ function factory$8(structs) { var outputVar = $$var(b); var codeEndRef = ""; var errorCodeRef = ""; - for(var idx$1 = 0 ,idx_finish$1 = structs.length; idx$1 < idx_finish$1; ++idx$1){ - var struct$1 = structs[idx$1]; + for(var idx$1 = 0 ,idx_finish$1 = schemas.length; idx$1 < idx_finish$1; ++idx$1){ + var schema$1 = schemas[idx$1]; var code = itemsCode[idx$1]; var itemOutputVar$1 = itemsOutputVar[idx$1]; - var isAsyncItem$1 = struct$1.i; + var isAsyncItem$1 = schema$1.i; var errorVar = varWithoutAllocation(b); var errorCode = isAsync ? ( isAsyncItem$1 ? errorVar + "===" + itemOutputVar$1 + "?" + errorVar + "():" : "" @@ -2411,31 +2411,31 @@ function factory$8(structs) { return outputVar; } }), - s: (function (b, selfStruct, path) { + s: (function (b, selfSchema, path) { var inputVar = toVar(b, b.i); - var structs = selfStruct.t._0; + var schemas = selfSchema.t._0; var outputVar = $$var(b); var codeEndRef = ""; var errorVarsRef = ""; - for(var idx = 0 ,idx_finish = structs.length; idx < idx_finish; ++idx){ - var itemStruct = structs[idx]; + for(var idx = 0 ,idx_finish = schemas.length; idx < idx_finish; ++idx){ + var itemSchema = schemas[idx]; var errorVar = varWithoutAllocation(b); errorVarsRef = errorVarsRef + errorVar + ","; - b.c = b.c + ("try{" + scope(b, (function(itemStruct){ + b.c = b.c + ("try{" + scope(b, (function(itemSchema){ return function (b) { - var itemOutput = use(b, itemStruct, inputVar, ""); - var typeFilter = itemStruct.f; + var itemOutput = use(b, itemSchema, inputVar, ""); + var typeFilter = itemSchema.f; var itemOutput$1; if (typeFilter !== undefined) { var itemOutputVar = toVar(b, itemOutput); - b.c = b.c + typeFilterCode(b, typeFilter, itemStruct, itemOutputVar, ""); + b.c = b.c + typeFilterCode(b, typeFilter, itemSchema, itemOutputVar, ""); itemOutput$1 = itemOutputVar; } else { itemOutput$1 = itemOutput; } return outputVar + "=" + itemOutput$1; } - }(itemStruct))) + "}catch(" + errorVar + "){if(" + (errorVar + "&&" + errorVar + ".s===s") + "){"); + }(itemSchema))) + "}catch(" + errorVar + "){if(" + (errorVar + "&&" + errorVar + ".s===s") + "){"); codeEndRef = "}else{throw " + errorVar + "}}" + codeEndRef; } b.c = b.c + raiseWithArg(b, path, (function (internalErrors) { @@ -2452,8 +2452,8 @@ function factory$8(structs) { }; } -function list(struct) { - return transform$1(factory$5(struct), (function (param) { +function list(schema) { + return transform$1(factory$5(schema), (function (param) { return { p: Belt_List.fromArray, s: Belt_List.toArray @@ -2464,7 +2464,7 @@ function list(struct) { var json = { t: "JSON", n: primitiveName, - p: (function (b, selfStruct, path) { + p: (function (b, selfSchema, path) { var parse = function (input, pathOpt) { var path$1 = pathOpt !== undefined ? pathOpt : path; var match = typeof input; @@ -2497,15 +2497,15 @@ var json = { if (!Number.isNaN(input)) { return input; } - throw new RescriptStructError({ + throw new RescriptSchemaError({ TAG: "InvalidType", - expected: selfStruct, + expected: selfSchema, received: input }, "Parsing", path$1); } - throw new RescriptStructError({ + throw new RescriptSchemaError({ TAG: "InvalidType", - expected: selfStruct, + expected: selfSchema, received: input }, "Parsing", path$1); }; @@ -2518,65 +2518,65 @@ var json = { m: empty }; -function $$catch(struct, getFallbackValue) { +function $$catch(schema, getFallbackValue) { return { - t: struct.t, - n: struct.n, - p: (function (b, selfStruct, path) { + t: schema.t, + n: schema.n, + p: (function (b, selfSchema, path) { var inputVar = toVar(b, b.i); return withCatch(b, (function (b, errorVar) { return "e[" + (b.e.push(function (input, internalError) { return getFallbackValue({ e: internalError, i: input, - s: selfStruct, + s: selfSchema, f: (function (message, customPathOpt) { var customPath = customPathOpt !== undefined ? customPathOpt : ""; - throw new RescriptStructError({ + throw new RescriptSchemaError({ TAG: "OperationFailed", _0: message }, b.o, path + customPath); }), w: (function (error) { - throw new RescriptStructError(error.code, b.o, path + error.path); + throw new RescriptSchemaError(error.code, b.o, path + error.path); }) }); }) - 1) + "](" + inputVar + "," + errorVar + ")"; }), (function (b) { - return useWithTypeFilter(b, struct, inputVar, path); + return useWithTypeFilter(b, schema, inputVar, path); })); }), - s: struct.s, + s: schema.s, f: undefined, i: 0, - m: struct.m + m: schema.m }; } -var deprecationMetadataId = "rescript-struct:deprecation"; +var deprecationMetadataId = "rescript-schema:deprecation"; -function deprecate(struct, message) { - return set$1(struct, deprecationMetadataId, message); +function deprecate(schema, message) { + return set$1(schema, deprecationMetadataId, message); } -function deprecation(struct) { - return struct.m[deprecationMetadataId]; +function deprecation(schema) { + return schema.m[deprecationMetadataId]; } -var descriptionMetadataId = "rescript-struct:description"; +var descriptionMetadataId = "rescript-schema:description"; -function describe(struct, description) { - return set$1(struct, descriptionMetadataId, description); +function describe(schema, description) { + return set$1(schema, descriptionMetadataId, description); } -function description(struct) { - return struct.m[descriptionMetadataId]; +function description(schema) { + return schema.m[descriptionMetadataId]; } -var $$class = RescriptStructError; +var $$class = RescriptSchemaError; function make$2(prim0, prim1, prim2) { - return new RescriptStructError(prim0, prim1, prim2); + return new RescriptSchemaError(prim0, prim1, prim2); } function raise(error) { @@ -2613,7 +2613,7 @@ function reason(error, nestedLevelOpt) { var reasons = Array.from(new Set(array)); return "Invalid union with following errors" + lineBreak + reasons.join(lineBreak); case "InvalidJsonStruct" : - return "The struct " + reason$1._0.n() + " is not compatible with JSON"; + return "The schema " + reason$1._0.n() + " is not compatible with JSON"; } } @@ -2627,60 +2627,60 @@ function message(error) { return "Failed " + operation + " at " + pathText + ". Reason: " + reason(error); } -function internalInline(struct, maybeVariant, param) { - var metadataMap = Object.assign({}, struct.m); - var literal = struct.t; - var inlinedStruct; +function internalInline(schema, maybeVariant, param) { + var metadataMap = Object.assign({}, schema.m); + var literal = schema.t; + var inlinedSchema; if (typeof literal !== "object") { switch (literal) { case "Never" : - inlinedStruct = "S.never"; + inlinedSchema = "S.never"; break; case "Unknown" : - inlinedStruct = "S.unknown"; + inlinedSchema = "S.unknown"; break; case "String" : - inlinedStruct = "S.string"; + inlinedSchema = "S.string"; break; case "Int" : - inlinedStruct = "S.int"; + inlinedSchema = "S.int"; break; case "Float" : - inlinedStruct = "S.float"; + inlinedSchema = "S.float"; break; case "Bool" : - inlinedStruct = "S.bool"; + inlinedSchema = "S.bool"; break; case "JSON" : - inlinedStruct = "S.json"; + inlinedSchema = "S.json"; break; } } else { switch (literal.TAG) { case "Literal" : - inlinedStruct = "S.literal(%raw(\`" + toText(literal._0) + "\`))"; + inlinedSchema = "S.literal(%raw(\`" + toText(literal._0) + "\`))"; break; case "Option" : - inlinedStruct = "S.option(" + internalInline(literal._0, undefined, undefined) + ")"; + inlinedSchema = "S.option(" + internalInline(literal._0, undefined, undefined) + ")"; break; case "Null" : - inlinedStruct = "S.null(" + internalInline(literal._0, undefined, undefined) + ")"; + inlinedSchema = "S.null(" + internalInline(literal._0, undefined, undefined) + ")"; break; case "Array" : - inlinedStruct = "S.array(" + internalInline(literal._0, undefined, undefined) + ")"; + inlinedSchema = "S.array(" + internalInline(literal._0, undefined, undefined) + ")"; break; case "Object" : var fieldNames = literal.fieldNames; var fields = literal.fields; - inlinedStruct = fieldNames.length !== 0 ? "S.object(s =>\n {\n " + fieldNames.map(function (fieldName) { + inlinedSchema = fieldNames.length !== 0 ? "S.object(s =>\n {\n " + fieldNames.map(function (fieldName) { return JSON.stringify(fieldName) + ": s.field(" + JSON.stringify(fieldName) + ", " + internalInline(fields[fieldName], undefined, undefined) + ")"; }).join(",\n ") + ",\n }\n)" : "S.object(_ => ())"; break; case "Tuple" : - var tupleStructs = literal._0; + var tupleSchemas = literal._0; var exit = 0; - var len = tupleStructs.length; + var len = tupleSchemas.length; if (len >= 4) { exit = 1; } else { @@ -2689,32 +2689,32 @@ function internalInline(struct, maybeVariant, param) { exit = 1; break; case 1 : - var s1 = tupleStructs[0]; - inlinedStruct = "S.tuple1(" + internalInline(s1, undefined, undefined) + ")"; + var s1 = tupleSchemas[0]; + inlinedSchema = "S.tuple1(" + internalInline(s1, undefined, undefined) + ")"; break; case 2 : - var s1$1 = tupleStructs[0]; - var s2 = tupleStructs[1]; - inlinedStruct = "S.tuple2(" + internalInline(s1$1, undefined, undefined) + ", " + internalInline(s2, undefined, undefined) + ")"; + var s1$1 = tupleSchemas[0]; + var s2 = tupleSchemas[1]; + inlinedSchema = "S.tuple2(" + internalInline(s1$1, undefined, undefined) + ", " + internalInline(s2, undefined, undefined) + ")"; break; case 3 : - var s1$2 = tupleStructs[0]; - var s2$1 = tupleStructs[1]; - var s3 = tupleStructs[2]; - inlinedStruct = "S.tuple3(" + internalInline(s1$2, undefined, undefined) + ", " + internalInline(s2$1, undefined, undefined) + ", " + internalInline(s3, undefined, undefined) + ")"; + var s1$2 = tupleSchemas[0]; + var s2$1 = tupleSchemas[1]; + var s3 = tupleSchemas[2]; + inlinedSchema = "S.tuple3(" + internalInline(s1$2, undefined, undefined) + ", " + internalInline(s2$1, undefined, undefined) + ", " + internalInline(s3, undefined, undefined) + ")"; break; } } if (exit === 1) { - inlinedStruct = "S.tuple(s => (" + tupleStructs.map(function (s, idx) { + inlinedSchema = "S.tuple(s => (" + tupleSchemas.map(function (s, idx) { return "s.item(" + idx + ", " + internalInline(s, undefined, undefined) + ")"; }).join(", ") + "))"; } break; case "Union" : var variantNamesCounter = {}; - inlinedStruct = "S.union([" + literal._0.map(function (s) { + inlinedSchema = "S.union([" + literal._0.map(function (s) { var variantName = s.n(); var n = Js_dict.get(variantNamesCounter, variantName); var numberOfVariantNames = n !== undefined ? n : 0; @@ -2725,40 +2725,40 @@ function internalInline(struct, maybeVariant, param) { }).join(", ") + "])"; break; case "Dict" : - inlinedStruct = "S.dict(" + internalInline(literal._0, undefined, undefined) + ")"; + inlinedSchema = "S.dict(" + internalInline(literal._0, undefined, undefined) + ")"; break; } } - var $$default = struct.m[defaultMetadataId]; - var inlinedStruct$1; + var $$default = schema.m[defaultMetadataId]; + var inlinedSchema$1; if ($$default !== undefined) { Js_dict.unsafeDeleteKey(metadataMap, defaultMetadataId); if ($$default.TAG === "Value") { var defaultValue = $$default._0; - inlinedStruct$1 = inlinedStruct + ("->S.Option.getOr(%raw(\`" + ( + inlinedSchema$1 = inlinedSchema + ("->S.Option.getOr(%raw(\`" + ( defaultValue === (void 0) ? "undefined" : JSON.stringify(defaultValue) ) + "\`))"); } else { var any = $$default._0(); - inlinedStruct$1 = inlinedStruct + ("->S.Option.getOrWith(() => %raw(\`" + ( + inlinedSchema$1 = inlinedSchema + ("->S.Option.getOrWith(() => %raw(\`" + ( any === (void 0) ? "undefined" : JSON.stringify(any) ) + "\`))"); } } else { - inlinedStruct$1 = inlinedStruct; + inlinedSchema$1 = inlinedSchema; } - var message = deprecation(struct); - var inlinedStruct$2 = message !== undefined ? (Js_dict.unsafeDeleteKey(metadataMap, deprecationMetadataId), inlinedStruct$1 + ("->S.deprecate(" + JSON.stringify(message) + ")")) : inlinedStruct$1; - var message$1 = description(struct); - var inlinedStruct$3 = message$1 !== undefined ? (Js_dict.unsafeDeleteKey(metadataMap, descriptionMetadataId), inlinedStruct$2 + ("->S.describe(" + ( + var message = deprecation(schema); + var inlinedSchema$2 = message !== undefined ? (Js_dict.unsafeDeleteKey(metadataMap, deprecationMetadataId), inlinedSchema$1 + ("->S.deprecate(" + JSON.stringify(message) + ")")) : inlinedSchema$1; + var message$1 = description(schema); + var inlinedSchema$3 = message$1 !== undefined ? (Js_dict.unsafeDeleteKey(metadataMap, descriptionMetadataId), inlinedSchema$2 + ("->S.describe(" + ( message$1 === (void 0) ? "undefined" : JSON.stringify(message$1) - ) + ")")) : inlinedStruct$2; - var match = struct.t; - var inlinedStruct$4; - inlinedStruct$4 = typeof match !== "object" || !(match.TAG === "Object" && match.unknownKeys !== "Strip") ? inlinedStruct$3 : inlinedStruct$3 + "->S.Object.strict"; - var match$1 = struct.t; - var inlinedStruct$5; + ) + ")")) : inlinedSchema$2; + var match = schema.t; + var inlinedSchema$4; + inlinedSchema$4 = typeof match !== "object" || !(match.TAG === "Object" && match.unknownKeys !== "Strip") ? inlinedSchema$3 : inlinedSchema$3 + "->S.Object.strict"; + var match$1 = schema.t; + var inlinedSchema$5; var exit$1 = 0; if (typeof match$1 !== "object") { switch (match$1) { @@ -2766,10 +2766,10 @@ function internalInline(struct, maybeVariant, param) { exit$1 = 1; break; case "Int" : - var refinements$4 = refinements$1(struct); + var refinements$4 = refinements$1(schema); if (refinements$4.length !== 0) { Js_dict.unsafeDeleteKey(metadataMap, metadataId$1); - inlinedStruct$5 = inlinedStruct$4 + refinements$4.map(function (refinement) { + inlinedSchema$5 = inlinedSchema$4 + refinements$4.map(function (refinement) { var match = refinement.kind; if (typeof match !== "object") { return "->S.Int.port(~message=" + JSON.stringify(refinement.message) + ")"; @@ -2780,14 +2780,14 @@ function internalInline(struct, maybeVariant, param) { } }).join(""); } else { - inlinedStruct$5 = inlinedStruct$4; + inlinedSchema$5 = inlinedSchema$4; } break; case "Float" : - var refinements$5 = refinements$2(struct); + var refinements$5 = refinements$2(schema); if (refinements$5.length !== 0) { Js_dict.unsafeDeleteKey(metadataMap, metadataId$2); - inlinedStruct$5 = inlinedStruct$4 + refinements$5.map(function (refinement) { + inlinedSchema$5 = inlinedSchema$4 + refinements$5.map(function (refinement) { var match = refinement.kind; if (match.TAG === "Min") { var value = match.value; @@ -2801,27 +2801,27 @@ function internalInline(struct, maybeVariant, param) { )) + ", ~message=" + JSON.stringify(refinement.message) + ")"; }).join(""); } else { - inlinedStruct$5 = inlinedStruct$4; + inlinedSchema$5 = inlinedSchema$4; } break; default: - inlinedStruct$5 = inlinedStruct$4; + inlinedSchema$5 = inlinedSchema$4; } } else { switch (match$1.TAG) { case "Literal" : var tmp = match$1._0; if (typeof tmp !== "object" || tmp.TAG !== "String") { - inlinedStruct$5 = inlinedStruct$4; + inlinedSchema$5 = inlinedSchema$4; } else { exit$1 = 1; } break; case "Array" : - var refinements$6 = refinements$3(struct); + var refinements$6 = refinements$3(schema); if (refinements$6.length !== 0) { Js_dict.unsafeDeleteKey(metadataMap, metadataId$3); - inlinedStruct$5 = inlinedStruct$4 + refinements$6.map(function (refinement) { + inlinedSchema$5 = inlinedSchema$4 + refinements$6.map(function (refinement) { var match = refinement.kind; switch (match.TAG) { case "Min" : @@ -2834,18 +2834,18 @@ function internalInline(struct, maybeVariant, param) { } }).join(""); } else { - inlinedStruct$5 = inlinedStruct$4; + inlinedSchema$5 = inlinedSchema$4; } break; default: - inlinedStruct$5 = inlinedStruct$4; + inlinedSchema$5 = inlinedSchema$4; } } if (exit$1 === 1) { - var refinements$7 = refinements(struct); + var refinements$7 = refinements(schema); if (refinements$7.length !== 0) { Js_dict.unsafeDeleteKey(metadataMap, metadataId); - inlinedStruct$5 = inlinedStruct$4 + refinements$7.map(function (refinement) { + inlinedSchema$5 = inlinedSchema$4 + refinements$7.map(function (refinement) { var match = refinement.kind; if (typeof match !== "object") { switch (match) { @@ -2876,18 +2876,18 @@ function internalInline(struct, maybeVariant, param) { } }).join(""); } else { - inlinedStruct$5 = inlinedStruct$4; + inlinedSchema$5 = inlinedSchema$4; } } - var inlinedStruct$6 = Object.keys(metadataMap).length !== 0 ? "{\n let s = " + inlinedStruct$5 + "\n let _ = %raw(\`s.m = " + JSON.stringify(metadataMap) + "\`)\n s\n}" : inlinedStruct$5; + var inlinedSchema$6 = Object.keys(metadataMap).length !== 0 ? "{\n let s = " + inlinedSchema$5 + "\n let _ = %raw(\`s.m = " + JSON.stringify(metadataMap) + "\`)\n s\n}" : inlinedSchema$5; if (maybeVariant !== undefined) { - return inlinedStruct$6 + ("->S.variant(v => " + maybeVariant + "(v))"); + return inlinedSchema$6 + ("->S.variant(v => " + maybeVariant + "(v))"); } else { - return inlinedStruct$6; + return inlinedSchema$6; } } -function inline(struct) { +function inline(schema) { if (false) { var v = (void 0); if (v !== undefined) { @@ -2895,7 +2895,7 @@ function inline(struct) { } } - return internalInline(struct, undefined, undefined); + return internalInline(schema, undefined, undefined); } function tuple1(v0) { @@ -2937,11 +2937,11 @@ function toJsResult(result) { } } -function js_parse(struct, data) { +function js_parse(schema, data) { try { return { success: true, - value: parseAnyOrRaiseWith(data, struct) + value: parseAnyOrRaiseWith(data, schema) }; } catch (raw_exn){ @@ -2953,19 +2953,19 @@ function js_parse(struct, data) { } } -function js_parseOrThrow(struct, data) { - return parseAnyOrRaiseWith(data, struct); +function js_parseOrThrow(schema, data) { + return parseAnyOrRaiseWith(data, schema); } -function js_parseAsync(struct, data) { - return parseAnyAsyncWith(data, struct).then(toJsResult); +function js_parseAsync(schema, data) { + return parseAnyAsyncWith(data, schema).then(toJsResult); } -function js_serialize(struct, value) { +function js_serialize(schema, value) { try { return { success: true, - value: serializeToUnknownOrRaiseWith(value, struct) + value: serializeToUnknownOrRaiseWith(value, schema) }; } catch (raw_exn){ @@ -2977,12 +2977,12 @@ function js_serialize(struct, value) { } } -function js_serializeOrThrow(struct, value) { - return serializeToUnknownOrRaiseWith(value, struct); +function js_serializeOrThrow(schema, value) { + return serializeToUnknownOrRaiseWith(value, schema); } -function js_transform(struct, maybeParser, maybeSerializer) { - return transform$1(struct, (function (s) { +function js_transform(schema, maybeParser, maybeSerializer) { + return transform$1(schema, (function (s) { return { p: maybeParser !== undefined ? (function (v) { return maybeParser(v, s); @@ -2994,8 +2994,8 @@ function js_transform(struct, maybeParser, maybeSerializer) { })); } -function js_refine(struct, refiner) { - return refine(struct, (function (s) { +function js_refine(schema, refiner) { + return refine(schema, (function (s) { return function (v) { refiner(v, s); }; @@ -3006,8 +3006,8 @@ function noop$1(a) { return a; } -function js_asyncParserRefine(struct, refine) { - return transform$1(struct, (function (s) { +function js_asyncParserRefine(schema, refine) { + return transform$1(schema, (function (s) { return { a: (function (v) { return function () { @@ -3021,16 +3021,16 @@ function js_asyncParserRefine(struct, refine) { })); } -function js_optional(struct, maybeOr) { - var struct$1 = factory$1(struct); +function js_optional(schema, maybeOr) { + var schema$1 = factory$1(schema); if (maybeOr === undefined) { - return struct$1; + return schema$1; } var or = Caml_option.valFromOption(maybeOr); if (typeof or === "function") { - return getOrWith(struct$1, or); + return getOrWith(schema$1, or); } else { - return getOr(struct$1, or); + return getOr(schema$1, or); } } @@ -3039,8 +3039,8 @@ function js_tuple(definer) { return factory$7(definer); } else { return factory$7(function (s) { - return definer.map(function (struct, idx) { - return s.i(idx, struct); + return definer.map(function (schema, idx) { + return s.i(idx, schema); }); }); } @@ -3068,8 +3068,8 @@ function js_object(definer) { var fieldNames = Object.keys(definer); for(var idx = 0 ,idx_finish = fieldNames.length; idx < idx_finish; ++idx){ var fieldName = fieldNames[idx]; - var struct = definer[fieldName]; - definition[fieldName] = s.f(fieldName, struct); + var schema = definer[fieldName]; + definition[fieldName] = s.f(fieldName, schema); } return definition; }); @@ -3096,7 +3096,7 @@ function js_merge(s1, s2) { var fieldName$1 = s2FieldNames[idx$1]; if (fields[fieldName$1]) { var message = "The field " + JSON.stringify(fieldName$1) + " is defined multiple times."; - throw new Error("[rescript-struct] " + message); + throw new Error("[rescript-schema] " + message); } fieldNames.push(fieldName$1); fields[fieldName$1] = s2Fields[fieldName$1]; @@ -3127,7 +3127,7 @@ function js_merge(s1, s2) { } } - throw new Error("[rescript-struct] The merge supports only Object structs."); + throw new Error("[rescript-schema] The merge supports only Object schemas."); } function js_name(prim) { @@ -3151,17 +3151,17 @@ var $$Error$1 = { reason: reason }; -var never = struct; +var never = schema; -var unknown = struct$1; +var unknown = schema$1; -var string = struct$2; +var string = schema$2; -var bool = struct$3; +var bool = schema$3; -var $$int = struct$4; +var $$int = schema$4; -var $$float = struct$5; +var $$float = schema$5; var array = factory$5; diff --git a/src/S_Core.res b/src/S_Core.res index d6b92711..69afe60b 100644 --- a/src/S_Core.res +++ b/src/S_Core.res @@ -320,7 +320,7 @@ module Path = { let concat = (path, concatedPath) => path ++ concatedPath } -let symbol = Stdlib.Symbol.make("rescript-struct") +let symbol = Stdlib.Symbol.make("rescript-schema") @unboxed type isAsyncParse = | @as(0) Unknown | Value(bool) @@ -380,21 +380,21 @@ and builderCtx = { and operation = | Parsing | Serializing -and struct<'a> = t<'a> +and schema<'a> = t<'a> type rec error = private {operation: operation, code: errorCode, path: Path.t} and errorCode = | OperationFailed(string) | InvalidOperation({description: string}) - | InvalidType({expected: struct, received: unknown}) + | InvalidType({expected: schema, received: unknown}) | InvalidLiteral({expected: Literal.t, received: unknown}) | InvalidTupleSize({expected: int, received: int}) | ExcessField(string) | InvalidUnion(array) | UnexpectedAsync - | InvalidJsonStruct(struct) + | InvalidJsonStruct(schema) type exn += private Raised(error) -external castUnknownStructToAnyStruct: t => t<'any> = "%identity" +external castUnknownSchemaToAnySchema: t => t<'any> = "%identity" external toUnknown: t<'any> => t = "%identity" type payloadedVariant<'payload> = private {_0: 'payload} @@ -404,7 +404,7 @@ let unsafeGetErrorPayload = variant => (variant->Obj.magic)._1 module InternalError = { %%raw(` - class RescriptStructError extends Error { + class RescriptSchemaError extends Error { constructor(code, operation, path) { super(); this.operation = operation; @@ -414,7 +414,7 @@ module InternalError = { this.RE_EXN_ID = Raised; this._1 = this; this.Error = this; - this.name = "RescriptStructError"; + this.name = "RescriptSchemaError"; } get message() { return message(this); @@ -427,7 +427,7 @@ module InternalError = { @new external make: (~code: errorCode, ~operation: operation, ~path: Path.t) => error = - "RescriptStructError" + "RescriptSchemaError" let getOrRethrow = (exn: exn) => { if %raw("exn&&exn.s===symbol") { @@ -452,18 +452,18 @@ module InternalError = { } @inline - let panic = message => Stdlib.Exn.raiseError(Stdlib.Exn.makeError(`[rescript-struct] ${message}`)) + let panic = message => Stdlib.Exn.raiseError(Stdlib.Exn.makeError(`[rescript-schema] ${message}`)) } type effectCtx<'value> = { - struct: t<'value>, + schema: t<'value>, fail: 'a. (string, ~path: Path.t=?) => 'a, failWithError: 'a. error => 'a, } module EffectCtx = { - let make = (~selfStruct, ~path, ~operation) => { - struct: selfStruct->castUnknownStructToAnyStruct, + let make = (~selfSchema, ~path, ~operation) => { + schema: selfSchema->castUnknownSchemaToAnySchema, failWithError: (error: error) => { InternalError.raise(~path=path->Path.concat(error.path), ~code=error.code, ~operation) }, @@ -478,12 +478,12 @@ module EffectCtx = { } @inline -let classify = struct => struct.tagged +let classify = schema => schema.tagged module Builder = { type t = builder type ctx = builderCtx - type implementation = (ctx, ~selfStruct: struct, ~path: Path.t) => string + type implementation = (ctx, ~selfSchema: schema, ~path: Path.t) => string let make = (Obj.magic: implementation => t) @@ -672,48 +672,48 @@ module Builder = { } } - let typeFilterCode = (b: t, ~typeFilter, ~struct, ~inputVar, ~path) => { + let typeFilterCode = (b: t, ~typeFilter, ~schema, ~inputVar, ~path) => { `if(${typeFilter(~inputVar)}){${b->raiseWithArg( ~path, input => InvalidType({ - expected: struct, + expected: schema, received: input, }), inputVar, )}}` } - let use = (b: t, ~struct, ~input, ~path) => { + let use = (b: t, ~schema, ~input, ~path) => { let isParentAsync = b.isAsyncBranch let isParsing = b.operation === Parsing b._input = input b.isAsyncBranch = false let output = ( - (isParsing ? struct.parseOperationBuilder : struct.serializeOperationBuilder)->( + (isParsing ? schema.parseOperationBuilder : schema.serializeOperationBuilder)->( Obj.magic: builder => implementation ) - )(b, ~selfStruct=struct, ~path) + )(b, ~selfSchema=schema, ~path) if isParsing { - struct.isAsyncParse = Value(b.isAsyncBranch) + schema.isAsyncParse = Value(b.isAsyncBranch) b.isAsyncBranch = isParentAsync || b.isAsyncBranch } output } - let useWithTypeFilter = (b: t, ~struct, ~input, ~path) => { - let input = switch struct.maybeTypeFilter { + let useWithTypeFilter = (b: t, ~schema, ~input, ~path) => { + let input = switch schema.maybeTypeFilter { | Some(typeFilter) => { let inputVar = b->toVar(input) - b.code = b.code ++ b->typeFilterCode(~struct, ~typeFilter, ~inputVar, ~path) + b.code = b.code ++ b->typeFilterCode(~schema, ~typeFilter, ~inputVar, ~path) inputVar } | None => input } - b->use(~struct, ~input, ~path) + b->use(~schema, ~input, ~path) } } - let noop = make((b, ~selfStruct as _, ~path as _) => { + let noop = make((b, ~selfSchema as _, ~path as _) => { b->Ctx.useInput }) @@ -722,7 +722,7 @@ module Builder = { @inline let intitialInputVar = "i" - let build = (builder, ~struct, ~operation) => { + let build = (builder, ~schema, ~operation) => { let b = { _embeded: [], _varCounter: -1, @@ -736,23 +736,23 @@ module Builder = { let output = (builder->(Obj.magic: builder => implementation))( b, - ~selfStruct=struct, + ~selfSchema=schema, ~path=Path.empty, ) if operation === Parsing { - switch struct.maybeTypeFilter { + switch schema.maybeTypeFilter { | Some(typeFilter) => b.code = b->Ctx.typeFilterCode( - ~struct, + ~schema, ~typeFilter, ~inputVar=intitialInputVar, ~path=Path.empty, ) ++ b.code | None => () } - struct.isAsyncParse = Value(b.isAsyncBranch) + schema.isAsyncParse = Value(b.isAsyncBranch) } if b.code === "" && output === intitialInputVar { @@ -778,11 +778,11 @@ module Builder = { module B = Builder.Ctx let toLiteral = { - let rec loop = struct => { - switch struct->classify { + let rec loop = schema => { + switch schema->classify { | Literal(literal) => literal - | Union(unionStructs) => unionStructs->Js.Array2.unsafe_get(0)->loop - | Tuple(tupleStructs) => Array(tupleStructs->Js.Array2.map(a => a->loop)) + | Union(unionSchemas) => unionSchemas->Js.Array2.unsafe_get(0)->loop + | Tuple(tupleSchemas) => Array(tupleSchemas->Js.Array2.map(a => a->loop)) | Object({fields}) => Dict(fields->Stdlib.Dict.mapValues(loop)) | String | Int @@ -798,9 +798,9 @@ let toLiteral = { Stdlib.Exn.raiseAny(symbol) } } - struct => { + schema => { try { - Some(loop(struct)) + Some(loop(schema)) } catch { | Js.Exn.Error(jsExn) => jsExn->(Obj.magic: Js.Exn.t => Stdlib.Symbol.t) === symbol ? None : Stdlib.Exn.raiseAny(jsExn) @@ -808,13 +808,13 @@ let toLiteral = { } } -let isAsyncParse = struct => { - let struct = struct->toUnknown - switch struct.isAsyncParse { +let isAsyncParse = schema => { + let schema = schema->toUnknown + switch schema.isAsyncParse { | Unknown => try { - let _ = struct.parseOperationBuilder->Builder.build(~struct, ~operation=Parsing) - struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let _ = schema.parseOperationBuilder->Builder.build(~schema, ~operation=Parsing) + schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) } catch { | exn => { let _ = exn->InternalError.getOrRethrow @@ -825,50 +825,50 @@ let isAsyncParse = struct => { } } -let rec validateJsonableStruct = (struct, ~rootStruct, ~isRoot=false) => { - if isRoot || rootStruct !== struct { - switch struct->classify { +let rec validateJsonableSchema = (schema, ~rootSchema, ~isRoot=false) => { + if isRoot || rootSchema !== schema { + switch schema->classify { | String | Int | Float | Bool | Never | JSON => () - | Dict(struct) - | Null(struct) - | Array(struct) => - struct->validateJsonableStruct(~rootStruct) + | Dict(schema) + | Null(schema) + | Array(schema) => + schema->validateJsonableSchema(~rootSchema) | Object({fieldNames, fields}) => for idx in 0 to fieldNames->Js.Array2.length - 1 { let fieldName = fieldNames->Js.Array2.unsafe_get(idx) - let fieldStruct = fields->Js.Dict.unsafeGet(fieldName) + let fieldSchema = fields->Js.Dict.unsafeGet(fieldName) try { - switch fieldStruct->classify { + switch fieldSchema->classify { // Allow optional fields | Option(s) => s - | _ => fieldStruct - }->validateJsonableStruct(~rootStruct) + | _ => fieldSchema + }->validateJsonableSchema(~rootSchema) } catch { | exn => exn->InternalError.prependLocationOrRethrow(fieldName) } } - | Tuple(childrenStructs) => - childrenStructs->Js.Array2.forEachi((struct, i) => { + | Tuple(childrenSchemas) => + childrenSchemas->Js.Array2.forEachi((schema, i) => { try { - struct->validateJsonableStruct(~rootStruct) + schema->validateJsonableSchema(~rootSchema) } catch { - // TODO: Should throw with the nested struct instead of prepending path? + // TODO: Should throw with the nested schema instead of prepending path? | exn => exn->InternalError.prependLocationOrRethrow(i->Js.Int.toString) } }) - | Union(childrenStructs) => - childrenStructs->Js.Array2.forEach(struct => struct->validateJsonableStruct(~rootStruct)) + | Union(childrenSchemas) => + childrenSchemas->Js.Array2.forEach(schema => schema->validateJsonableSchema(~rootSchema)) | Literal(l) if l->Literal.isJsonable => () | Option(_) | Unknown | Literal(_) => - InternalError.raise(~path=Path.empty, ~code=InvalidJsonStruct(struct), ~operation=Serializing) + InternalError.raise(~path=Path.empty, ~code=InvalidJsonStruct(schema), ~operation=Serializing) } } } @@ -936,15 +936,15 @@ module Operation = { } } -let parseAnyOrRaiseWith = Operation.make(~label=Parser, ~init=struct => { - let operation = struct.parseOperationBuilder->Builder.build(~struct, ~operation=Parsing) - let isAsync = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) +let parseAnyOrRaiseWith = Operation.make(~label=Parser, ~init=schema => { + let operation = schema.parseOperationBuilder->Builder.build(~schema, ~operation=Parsing) + let isAsync = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) isAsync ? Operation.unexpectedAsync : operation }) -let parseAnyWith = (any, struct) => { +let parseAnyWith = (any, schema) => { try { - parseAnyOrRaiseWith(any->castAnyToUnknown, struct)->castUnknownToAny->Ok + parseAnyOrRaiseWith(any->castAnyToUnknown, schema)->castUnknownToAny->Ok } catch { | exn => exn->InternalError.getOrRethrow->Error } @@ -960,9 +960,9 @@ let asyncPrepareError = jsExn => { jsExn->(Obj.magic: Js.Exn.t => exn)->InternalError.getOrRethrow->Error } -let internalParseAsyncWith = Operation.make(~label=ParserAsync, ~init=struct => { - let operation = struct.parseOperationBuilder->Builder.build(~struct, ~operation=Parsing) - let isAsync = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) +let internalParseAsyncWith = Operation.make(~label=ParserAsync, ~init=schema => { + let operation = schema.parseOperationBuilder->Builder.build(~schema, ~operation=Parsing) + let isAsync = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) isAsync ? operation->(Obj.magic: (unknown => unknown) => unknown => unit => promise) : input => { @@ -971,9 +971,9 @@ let internalParseAsyncWith = Operation.make(~label=ParserAsync, ~init=struct => } }) -let parseAnyAsyncWith = (any, struct) => { +let parseAnyAsyncWith = (any, schema) => { try { - internalParseAsyncWith(any->castAnyToUnknown, struct)()->Stdlib.Promise.thenResolveWithCatch( + internalParseAsyncWith(any->castAnyToUnknown, schema)()->Stdlib.Promise.thenResolveWithCatch( asyncPrepareOk, asyncPrepareError, ) @@ -984,9 +984,9 @@ let parseAnyAsyncWith = (any, struct) => { let parseAsyncWith = parseAnyAsyncWith -let parseAnyAsyncInStepsWith = (any, struct) => { +let parseAnyAsyncInStepsWith = (any, schema) => { try { - let asyncFn = internalParseAsyncWith(any->castAnyToUnknown, struct) + let asyncFn = internalParseAsyncWith(any->castAnyToUnknown, schema) (() => asyncFn()->Stdlib.Promise.thenResolveWithCatch(asyncPrepareOk, asyncPrepareError))->Ok } catch { | exn => exn->InternalError.getOrRethrow->Error @@ -995,42 +995,42 @@ let parseAnyAsyncInStepsWith = (any, struct) => { let parseAsyncInStepsWith = parseAnyAsyncInStepsWith -let serializeOrRaiseWith = Operation.make(~label=SerializerToJson, ~init=struct => { - struct->validateJsonableStruct(~rootStruct=struct, ~isRoot=true) - struct.serializeOperationBuilder->Builder.build(~struct, ~operation=Serializing) +let serializeOrRaiseWith = Operation.make(~label=SerializerToJson, ~init=schema => { + schema->validateJsonableSchema(~rootSchema=schema, ~isRoot=true) + schema.serializeOperationBuilder->Builder.build(~schema, ~operation=Serializing) }) -let serializeWith = (value, struct) => { +let serializeWith = (value, schema) => { try { - serializeOrRaiseWith(value, struct)->Ok + serializeOrRaiseWith(value, schema)->Ok } catch { | exn => exn->InternalError.getOrRethrow->Error } } -let serializeToUnknownOrRaiseWith = Operation.make(~label=Serializer, ~init=struct => { - struct.serializeOperationBuilder->Builder.build(~struct, ~operation=Serializing) +let serializeToUnknownOrRaiseWith = Operation.make(~label=Serializer, ~init=schema => { + schema.serializeOperationBuilder->Builder.build(~schema, ~operation=Serializing) }) -let serializeToUnknownWith = (value, struct) => { +let serializeToUnknownWith = (value, schema) => { try { - serializeToUnknownOrRaiseWith(value, struct)->Ok + serializeToUnknownOrRaiseWith(value, schema)->Ok } catch { | exn => exn->InternalError.getOrRethrow->Error } } -let serializeToJsonStringWith = (value: 'value, struct: t<'value>, ~space=0): result< +let serializeToJsonStringWith = (value: 'value, schema: t<'value>, ~space=0): result< string, error, > => { - switch value->serializeWith(struct) { + switch value->serializeWith(schema) { | Ok(json) => Ok(json->Js.Json.stringifyWithSpace(space)) | Error(_) as e => e } } -let parseJsonStringWith = (json: string, struct: t<'value>): result<'value, error> => { +let parseJsonStringWith = (json: string, schema: t<'value>): result<'value, error> => { switch try { json->Js.Json.parseExn->Ok } catch { @@ -1043,7 +1043,7 @@ let parseJsonStringWith = (json: string, struct: t<'value>): result<'value, erro ), ) } { - | Ok(json) => json->parseWith(struct) + | Ok(json) => json->parseWith(schema) | Error(_) as e => e } } @@ -1077,18 +1077,18 @@ module Metadata = { } } - let get = (struct, ~id: Id.t<'metadata>) => { - struct.metadataMap->Js.Dict.unsafeGet(id->Id.toKey)->(Obj.magic: unknown => option<'metadata>) + let get = (schema, ~id: Id.t<'metadata>) => { + schema.metadataMap->Js.Dict.unsafeGet(id->Id.toKey)->(Obj.magic: unknown => option<'metadata>) } - let set = (struct, ~id: Id.t<'metadata>, metadata: 'metadata) => { - let metadataMap = struct.metadataMap->Map.set(~id, metadata) + let set = (schema, ~id: Id.t<'metadata>, metadata: 'metadata) => { + let metadataMap = schema.metadataMap->Map.set(~id, metadata) make( - ~name=struct.name, - ~parseOperationBuilder=struct.parseOperationBuilder, - ~serializeOperationBuilder=struct.serializeOperationBuilder, - ~tagged=struct.tagged, - ~maybeTypeFilter=struct.maybeTypeFilter, + ~name=schema.name, + ~parseOperationBuilder=schema.parseOperationBuilder, + ~serializeOperationBuilder=schema.serializeOperationBuilder, + ~tagged=schema.tagged, + ~maybeTypeFilter=schema.maybeTypeFilter, ~metadataMap, ) } @@ -1096,15 +1096,15 @@ module Metadata = { let recursive = fn => { let placeholder: t<'value> = {"m": Metadata.Map.empty}->Obj.magic - let struct = fn(placeholder) - placeholder->Stdlib.Object.overrideWith(struct) + let schema = fn(placeholder) + placeholder->Stdlib.Object.overrideWith(schema) { let builder = placeholder.parseOperationBuilder - placeholder.parseOperationBuilder = Builder.make((b, ~selfStruct, ~path) => { + placeholder.parseOperationBuilder = Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput let isAsync = { - selfStruct.parseOperationBuilder = Builder.noop + selfSchema.parseOperationBuilder = Builder.noop let ctx = { _embeded: [], _varsAllocation: "", @@ -1115,28 +1115,28 @@ let recursive = fn => { isAsyncBranch: false, operation: Parsing, } - let _ = (builder->(Obj.magic: builder => Builder.implementation))(ctx, ~selfStruct, ~path) + let _ = (builder->(Obj.magic: builder => Builder.implementation))(ctx, ~selfSchema, ~path) ctx.isAsyncBranch } - selfStruct.parseOperationBuilder = Builder.make((b, ~selfStruct, ~path as _) => { + selfSchema.parseOperationBuilder = Builder.make((b, ~selfSchema, ~path as _) => { let input = b->B.useInput if isAsync { - b->B.embedAsyncOperation(~input, ~fn=input => input->internalParseAsyncWith(selfStruct)) + b->B.embedAsyncOperation(~input, ~fn=input => input->internalParseAsyncWith(selfSchema)) } else { - b->B.embedSyncOperation(~input, ~fn=input => input->parseAnyOrRaiseWith(selfStruct)) + b->B.embedSyncOperation(~input, ~fn=input => input->parseAnyOrRaiseWith(selfSchema)) } }) - let operation = builder->Builder.build(~struct=selfStruct, ~operation=Parsing) + let operation = builder->Builder.build(~schema=selfSchema, ~operation=Parsing) if isAsync { - selfStruct->Obj.magic->Js.Dict.set((Operation.ParserAsync :> string), operation) + selfSchema->Obj.magic->Js.Dict.set((Operation.ParserAsync :> string), operation) } else { // TODO: Use init function - selfStruct->Obj.magic->Js.Dict.set((Operation.Parser :> string), operation) + selfSchema->Obj.magic->Js.Dict.set((Operation.Parser :> string), operation) } - selfStruct.parseOperationBuilder = builder + selfSchema.parseOperationBuilder = builder b->B.withPathPrepend(~path, (b, ~path as _) => if isAsync { b->B.embedAsyncOperation(~input, ~fn=operation) @@ -1149,23 +1149,23 @@ let recursive = fn => { { let builder = placeholder.serializeOperationBuilder - placeholder.serializeOperationBuilder = Builder.make((b, ~selfStruct, ~path) => { + placeholder.serializeOperationBuilder = Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - selfStruct.serializeOperationBuilder = Builder.make((b, ~selfStruct, ~path as _) => { + selfSchema.serializeOperationBuilder = Builder.make((b, ~selfSchema, ~path as _) => { let input = b->B.useInput b->B.embedSyncOperation( ~input, - ~fn=input => input->serializeToUnknownOrRaiseWith(selfStruct), + ~fn=input => input->serializeToUnknownOrRaiseWith(selfSchema), ) }) - let operation = builder->Builder.build(~struct=selfStruct, ~operation=Serializing) + let operation = builder->Builder.build(~schema=selfSchema, ~operation=Serializing) // TODO: Use init function // TODO: What about json validation ?? Check whether it works correctly - selfStruct->Obj.magic->Js.Dict.set((Operation.Serializer :> string), operation) + selfSchema->Obj.magic->Js.Dict.set((Operation.Serializer :> string), operation) - selfStruct.serializeOperationBuilder = builder + selfSchema.serializeOperationBuilder = builder b->B.withPathPrepend(~path, (b, ~path as _) => b->B.embedSyncOperation(~input, ~fn=operation)) }) } @@ -1173,14 +1173,14 @@ let recursive = fn => { placeholder } -let setName = (struct, name) => { +let setName = (schema, name) => { make( ~name=() => name, - ~parseOperationBuilder=struct.parseOperationBuilder, - ~serializeOperationBuilder=struct.serializeOperationBuilder, - ~tagged=struct.tagged, - ~maybeTypeFilter=struct.maybeTypeFilter, - ~metadataMap=struct.metadataMap, + ~parseOperationBuilder=schema.parseOperationBuilder, + ~serializeOperationBuilder=schema.serializeOperationBuilder, + ~tagged=schema.tagged, + ~maybeTypeFilter=schema.maybeTypeFilter, + ~metadataMap=schema.metadataMap, ) } @@ -1193,49 +1193,49 @@ let containerName = () => { `${tagged["TAG"]}(${(tagged->unsafeGetVariantPayload).name()})` } -let internalRefine = (struct, refiner) => { - let struct = struct->toUnknown +let internalRefine = (schema, refiner) => { + let schema = schema->toUnknown make( - ~name=struct.name, - ~tagged=struct.tagged, - ~parseOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~name=schema.name, + ~tagged=schema.tagged, + ~parseOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - b->B.transform(~input=b->B.use(~struct, ~input, ~path), ~isAsync=false, (b, ~input) => { + b->B.transform(~input=b->B.use(~schema, ~input, ~path), ~isAsync=false, (b, ~input) => { let inputVar = b->B.toVar(input) - b.code = b.code ++ refiner(b, ~inputVar, ~selfStruct, ~path) + b.code = b.code ++ refiner(b, ~inputVar, ~selfSchema, ~path) inputVar }) }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput b->B.use( - ~struct, + ~schema, ~input=b->B.transform(~input, ~isAsync=false, (b, ~input) => { let inputVar = b->B.toVar(input) - b.code = b.code ++ refiner(b, ~inputVar, ~selfStruct, ~path) + b.code = b.code ++ refiner(b, ~inputVar, ~selfSchema, ~path) inputVar }), ~path, ) }), - ~maybeTypeFilter=struct.maybeTypeFilter, - ~metadataMap=struct.metadataMap, + ~maybeTypeFilter=schema.maybeTypeFilter, + ~metadataMap=schema.metadataMap, ) } -let refine: (t<'value>, effectCtx<'value> => 'value => unit) => t<'value> = (struct, refiner) => { - struct->internalRefine((b, ~inputVar, ~selfStruct, ~path) => { +let refine: (t<'value>, effectCtx<'value> => 'value => unit) => t<'value> = (schema, refiner) => { + schema->internalRefine((b, ~inputVar, ~selfSchema, ~path) => { `${b->B.embed( - refiner(EffectCtx.make(~selfStruct, ~path, ~operation=b.operation)), + refiner(EffectCtx.make(~selfSchema, ~path, ~operation=b.operation)), )}(${inputVar});` }) } -let addRefinement = (struct, ~metadataId, ~refinement, ~refiner) => { - struct +let addRefinement = (schema, ~metadataId, ~refinement, ~refiner) => { + schema ->Metadata.set( ~id=metadataId, - switch struct->Metadata.get(~id=metadataId) { + switch schema->Metadata.get(~id=metadataId) { | Some(refinements) => refinements->Stdlib.Array.append(refinement) | None => [refinement] }, @@ -1254,15 +1254,15 @@ type transformDefinition<'input, 'output> = { let transform: ( t<'input>, effectCtx<'output> => transformDefinition<'input, 'output>, -) => t<'output> = (struct, transformer) => { - let struct = struct->toUnknown +) => t<'output> = (schema, transformer) => { + let schema = schema->toUnknown make( - ~name=struct.name, - ~tagged=struct.tagged, - ~parseOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~name=schema.name, + ~tagged=schema.tagged, + ~parseOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - let input = b->B.use(~struct, ~input, ~path) - switch transformer(EffectCtx.make(~selfStruct, ~path, ~operation=b.operation)) { + let input = b->B.use(~schema, ~input, ~path) + switch transformer(EffectCtx.make(~selfSchema, ~path, ~operation=b.operation)) { | {parser, asyncParser: ?None} => b->B.embedSyncOperation(~input, ~fn=parser) | {parser: ?None, asyncParser} => b->B.embedAsyncOperation(~input, ~fn=asyncParser) | {parser: ?None, asyncParser: ?None, serializer: ?None} => input @@ -1275,19 +1275,19 @@ let transform: ( ) } }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - switch transformer(EffectCtx.make(~selfStruct, ~path, ~operation=b.operation)) { + switch transformer(EffectCtx.make(~selfSchema, ~path, ~operation=b.operation)) { | {serializer} => - b->B.use(~struct, ~input=b->B.embedSyncOperation(~input, ~fn=serializer), ~path) - | {parser: ?None, asyncParser: ?None, serializer: ?None} => b->B.use(~struct, ~input, ~path) + b->B.use(~schema, ~input=b->B.embedSyncOperation(~input, ~fn=serializer), ~path) + | {parser: ?None, asyncParser: ?None, serializer: ?None} => b->B.use(~schema, ~input, ~path) | {serializer: ?None, asyncParser: ?Some(_)} | {serializer: ?None, parser: ?Some(_)} => b->B.invalidOperation(~path, ~description=`The S.transform serializer is missing`) } }), - ~maybeTypeFilter=struct.maybeTypeFilter, - ~metadataMap=struct.metadataMap, + ~maybeTypeFilter=schema.maybeTypeFilter, + ~metadataMap=schema.metadataMap, ) } @@ -1299,33 +1299,33 @@ type preprocessDefinition<'input, 'output> = { @as("s") serializer?: unknown => 'input, } -let rec preprocess = (struct, transformer) => { - let struct = struct->toUnknown - switch struct->classify { - | Union(unionStructs) => +let rec preprocess = (schema, transformer) => { + let schema = schema->toUnknown + switch schema->classify { + | Union(unionSchemas) => make( - ~name=struct.name, + ~name=schema.name, ~tagged=Union( - unionStructs->Js.Array2.map(unionStruct => - unionStruct->castUnknownStructToAnyStruct->preprocess(transformer)->toUnknown + unionSchemas->Js.Array2.map(unionSchema => + unionSchema->castUnknownSchemaToAnySchema->preprocess(transformer)->toUnknown ), ), - ~parseOperationBuilder=struct.parseOperationBuilder, - ~serializeOperationBuilder=struct.serializeOperationBuilder, - ~maybeTypeFilter=struct.maybeTypeFilter, - ~metadataMap=struct.metadataMap, + ~parseOperationBuilder=schema.parseOperationBuilder, + ~serializeOperationBuilder=schema.serializeOperationBuilder, + ~maybeTypeFilter=schema.maybeTypeFilter, + ~metadataMap=schema.metadataMap, ) | _ => make( - ~name=struct.name, - ~tagged=struct.tagged, - ~parseOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~name=schema.name, + ~tagged=schema.tagged, + ~parseOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - switch transformer(EffectCtx.make(~selfStruct, ~path, ~operation=b.operation)) { + switch transformer(EffectCtx.make(~selfSchema, ~path, ~operation=b.operation)) { | {parser, asyncParser: ?None} => let operationResultVar = b->B.var b.code = b.code ++ `${operationResultVar}=${b->B.embedSyncOperation(~input, ~fn=parser)};` - b->B.useWithTypeFilter(~struct, ~input=operationResultVar, ~path) + b->B.useWithTypeFilter(~schema, ~input=operationResultVar, ~path) | {parser: ?None, asyncParser} => { let parseResultVar = b->B.embedAsyncOperation(~input, ~fn=asyncParser) let outputVar = b->B.var @@ -1335,14 +1335,14 @@ let rec preprocess = (struct, transformer) => { b.code = b.code ++ `${outputVar}=()=>${parseResultVar}().then(${asyncResultVar}=>{${b->B.scope(b => { - let structOutputVar = - b->B.useWithTypeFilter(~struct, ~input=asyncResultVar, ~path) - let isAsync = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) - `return ${isAsync ? `${structOutputVar}()` : structOutputVar}` + let schemaOutputVar = + b->B.useWithTypeFilter(~schema, ~input=asyncResultVar, ~path) + let isAsync = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) + `return ${isAsync ? `${schemaOutputVar}()` : schemaOutputVar}` })}});` outputVar } - | {parser: ?None, asyncParser: ?None} => b->B.useWithTypeFilter(~struct, ~input, ~path) + | {parser: ?None, asyncParser: ?None} => b->B.useWithTypeFilter(~schema, ~input, ~path) | {parser: _, asyncParser: _} => b->B.invalidOperation( ~path, @@ -1350,17 +1350,17 @@ let rec preprocess = (struct, transformer) => { ) } }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - let input = b->B.use(~struct, ~input, ~path) - switch transformer(EffectCtx.make(~selfStruct, ~path, ~operation=b.operation)) { + let input = b->B.use(~schema, ~input, ~path) + switch transformer(EffectCtx.make(~selfSchema, ~path, ~operation=b.operation)) { | {serializer} => b->B.embedSyncOperation(~input, ~fn=serializer) // TODO: Test that it doesn't return InvalidOperation when parser is passed but not serializer | {serializer: ?None} => input } }), ~maybeTypeFilter=None, - ~metadataMap=struct.metadataMap, + ~metadataMap=schema.metadataMap, ) } } @@ -1378,9 +1378,9 @@ let custom = (name, definer) => { ~name=() => name, ~metadataMap=Metadata.Map.empty, ~tagged=Unknown, - ~parseOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~parseOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - switch definer(EffectCtx.make(~selfStruct, ~path, ~operation=b.operation)) { + switch definer(EffectCtx.make(~selfSchema, ~path, ~operation=b.operation)) { | {parser, asyncParser: ?None} => b->B.embedSyncOperation(~input, ~fn=parser) | {parser: ?None, asyncParser} => b->B.embedAsyncOperation(~input, ~fn=asyncParser) | {parser: ?None, asyncParser: ?None, serializer: ?None} => input @@ -1393,9 +1393,9 @@ let custom = (name, definer) => { ) } }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput - switch definer(EffectCtx.make(~selfStruct, ~path, ~operation=b.operation)) { + switch definer(EffectCtx.make(~selfSchema, ~path, ~operation=b.operation)) { | {serializer} => b->B.embedSyncOperation(~input, ~fn=serializer) | {parser: ?None, asyncParser: ?None, serializer: ?None} => input | {serializer: ?None, asyncParser: ?Some(_)} @@ -1457,7 +1457,7 @@ let rec literalCheckBuilder = (b, ~value, ~inputVar) => { let literal = value => { let value = value->castAnyToUnknown let literal = value->Literal.classify - let operationBuilder = Builder.make((b, ~selfStruct as _, ~path) => { + let operationBuilder = Builder.make((b, ~selfSchema as _, ~path) => { let inputVar = b->B.useInputVar b.code = b.code ++ @@ -1518,16 +1518,16 @@ module Variant = { type serializeOutput = Registered(string) | @as(0) Unregistered | @as(1) RegisteredMultipleTimes let factory = { - (struct: t<'value>, definer: 'value => 'variant): t<'variant> => { - let struct = struct->toUnknown + (schema: t<'value>, definer: 'value => 'variant): t<'variant> => { + let schema = schema->toUnknown make( - ~name=struct.name, - ~tagged=struct.tagged, - ~parseOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~name=schema.name, + ~tagged=schema.tagged, + ~parseOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let input = b->B.useInput - b->B.embedSyncOperation(~input=b->B.use(~struct, ~input, ~path), ~fn=definer) + b->B.embedSyncOperation(~input=b->B.use(~schema, ~input, ~path), ~fn=definer) }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let inputVar = b->B.useInputVar let definition = @@ -1594,10 +1594,10 @@ module Variant = { ~path, ~description=`Can't create serializer. The S.variant's value is registered multiple times. Use S.transform instead`, ) - | Registered(var) => b->B.use(~struct, ~input=var, ~path) + | Registered(var) => b->B.use(~schema, ~input=var, ~path) | Unregistered => - switch selfStruct->toLiteral { - | Some(literal) => b->B.use(~struct, ~input=b->B.embed(literal->Literal.value), ~path) + switch selfSchema->toLiteral { + | Some(literal) => b->B.use(~schema, ~input=b->B.embed(literal->Literal.value), ~path) | None => b->B.invalidOperation( ~path, @@ -1606,8 +1606,8 @@ module Variant = { } } }), - ~maybeTypeFilter=struct.maybeTypeFilter, - ~metadataMap=struct.metadataMap, + ~maybeTypeFilter=schema.maybeTypeFilter, + ~metadataMap=schema.metadataMap, ) } } @@ -1617,23 +1617,23 @@ module Option = { type default = Value(unknown) | Callback(unit => unknown) let defaultMetadataId: Metadata.Id.t = Metadata.Id.make( - ~namespace="rescript-struct", + ~namespace="rescript-schema", ~name="Option.default", ) - let default = struct => struct->Metadata.get(~id=defaultMetadataId) + let default = schema => schema->Metadata.get(~id=defaultMetadataId) - let parseOperationBuilder = Builder.make((b, ~selfStruct, ~path) => { + let parseOperationBuilder = Builder.make((b, ~selfSchema, ~path) => { let inputVar = b->B.useInputVar let outputVar = b->B.var - let isNull = %raw(`selfStruct.t.TAG === "Null"`) - let childStruct = selfStruct.tagged->unsafeGetVariantPayload + let isNull = %raw(`selfSchema.t.TAG === "Null"`) + let childSchema = selfSchema.tagged->unsafeGetVariantPayload let ifCode = b->B.scope(b => { - `${outputVar}=${b->B.use(~struct=childStruct, ~input=inputVar, ~path)}` + `${outputVar}=${b->B.use(~schema=childSchema, ~input=inputVar, ~path)}` }) - let isAsync = childStruct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let isAsync = childSchema.isAsyncParse->(Obj.magic: isAsyncParse => bool) b.code = b.code ++ @@ -1647,18 +1647,18 @@ module Option = { outputVar }) - let serializeOperationBuilder = Builder.make((b, ~selfStruct, ~path) => { + let serializeOperationBuilder = Builder.make((b, ~selfSchema, ~path) => { let inputVar = b->B.useInputVar let outputVar = b->B.var - let isNull = %raw(`selfStruct.t.TAG === "Null"`) - let childStruct = selfStruct.tagged->unsafeGetVariantPayload + let isNull = %raw(`selfSchema.t.TAG === "Null"`) + let childSchema = selfSchema.tagged->unsafeGetVariantPayload b.code = b.code ++ `if(${inputVar}!==void 0){${b->B.scope(b => { `${outputVar}=${b->B.use( - ~struct=childStruct, + ~schema=childSchema, ~input=`${b->B.embed(%raw("Caml_option.valFromOption"))}(${inputVar})`, ~path, )}` @@ -1666,8 +1666,8 @@ module Option = { outputVar }) - let maybeTypeFilter = (~struct, ~inlinedNoneValue) => { - switch struct.maybeTypeFilter { + let maybeTypeFilter = (~schema, ~inlinedNoneValue) => { + switch schema.maybeTypeFilter { | Some(typeFilter) => Some( (~inputVar) => { @@ -1678,27 +1678,27 @@ module Option = { } } - let factory = struct => { - let struct = struct->toUnknown + let factory = schema => { + let schema = schema->toUnknown make( ~name=containerName, ~metadataMap=Metadata.Map.empty, - ~tagged=Option(struct), + ~tagged=Option(schema), ~parseOperationBuilder, ~serializeOperationBuilder, - ~maybeTypeFilter=maybeTypeFilter(~struct, ~inlinedNoneValue="void 0"), + ~maybeTypeFilter=maybeTypeFilter(~schema, ~inlinedNoneValue="void 0"), ) } - let getWithDefault = (struct, default) => { - let struct = struct->(Obj.magic: t> => t) + let getWithDefault = (schema, default) => { + let schema = schema->(Obj.magic: t> => t) make( - ~name=struct.name, - ~metadataMap=struct.metadataMap->Metadata.Map.set(~id=defaultMetadataId, default), - ~tagged=struct.tagged, - ~parseOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~name=schema.name, + ~metadataMap=schema.metadataMap->Metadata.Map.set(~id=defaultMetadataId, default), + ~tagged=schema.tagged, + ~parseOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let input = b->B.useInput - b->B.transform(~input=b->B.use(~struct, ~input, ~path), ~isAsync=false, (b, ~input) => { + b->B.transform(~input=b->B.use(~schema, ~input, ~path), ~isAsync=false, (b, ~input) => { // TODO: Reassign input if it's not a var `${input}===void 0?${switch default { | Value(v) => b->B.embed(v) @@ -1706,27 +1706,27 @@ module Option = { }}:${input}` }) }), - ~serializeOperationBuilder=struct.serializeOperationBuilder, - ~maybeTypeFilter=struct.maybeTypeFilter, + ~serializeOperationBuilder=schema.serializeOperationBuilder, + ~maybeTypeFilter=schema.maybeTypeFilter, ) } - let getOr = (struct, defalutValue) => - struct->getWithDefault(Value(defalutValue->castAnyToUnknown)) - let getOrWith = (struct, defalutCb) => - struct->getWithDefault(Callback(defalutCb->(Obj.magic: (unit => 'a) => unit => unknown))) + let getOr = (schema, defalutValue) => + schema->getWithDefault(Value(defalutValue->castAnyToUnknown)) + let getOrWith = (schema, defalutCb) => + schema->getWithDefault(Callback(defalutCb->(Obj.magic: (unit => 'a) => unit => unknown))) } module Null = { - let factory = struct => { - let struct = struct->toUnknown + let factory = schema => { + let schema = schema->toUnknown make( ~name=containerName, ~metadataMap=Metadata.Map.empty, - ~tagged=Null(struct), + ~tagged=Null(schema), ~parseOperationBuilder=Option.parseOperationBuilder, ~serializeOperationBuilder=Option.serializeOperationBuilder, - ~maybeTypeFilter=Option.maybeTypeFilter(~struct, ~inlinedNoneValue="null"), + ~maybeTypeFilter=Option.maybeTypeFilter(~schema, ~inlinedNoneValue="null"), ) } } @@ -1739,7 +1739,7 @@ module Object = { } type itemDefinition = { @as("s") - struct: struct, + schema: schema, @as("l") inlinedInputLocation: string, @as("p") @@ -1748,7 +1748,7 @@ module Object = { let typeFilter = (~inputVar) => `!${inputVar}||${inputVar}.constructor!==Object` - let noopRefinement = (_b, ~selfStruct as _, ~inputVar as _, ~path as _) => () + let noopRefinement = (_b, ~selfSchema as _, ~inputVar as _, ~path as _) => () let makeParseOperationBuilder = ( ~itemDefinitions, @@ -1757,17 +1757,17 @@ module Object = { ~inputRefinement, ~unknownKeysRefinement, ) => { - Builder.make((b, ~selfStruct, ~path) => { + Builder.make((b, ~selfSchema, ~path) => { let inputVar = b->B.useInputVar let registeredDefinitions = Stdlib.Set.empty() let asyncOutputVars = [] - inputRefinement(b, ~selfStruct, ~inputVar, ~path) + inputRefinement(b, ~selfSchema, ~inputVar, ~path) let prevCode = b.code b.code = "" - unknownKeysRefinement(b, ~selfStruct, ~inputVar, ~path) + unknownKeysRefinement(b, ~selfSchema, ~inputVar, ~path) let unknownKeysRefinementCode = b.code b.code = "" @@ -1778,14 +1778,14 @@ module Object = { | Embeded => { let itemDefinition = definition->Definition.toEmbeded registeredDefinitions->Stdlib.Set.add(itemDefinition)->ignore - let {struct, inputPath} = itemDefinition + let {schema, inputPath} = itemDefinition let fieldOuputVar = b->B.useWithTypeFilter( - ~struct, + ~schema, ~input=`${inputVar}${inputPath}`, ~path=path->Path.concat(inputPath), ) - let isAsyncField = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let isAsyncField = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) if isAsyncField { // TODO: Ensure that it's not a var, but inlined asyncOutputVars->Js.Array2.push(fieldOuputVar)->ignore @@ -1825,14 +1825,14 @@ module Object = { for idx in 0 to itemDefinitions->Js.Array2.length - 1 { let itemDefinition = itemDefinitions->Js.Array2.unsafe_get(idx) if registeredDefinitions->Stdlib.Set.has(itemDefinition)->not { - let {struct, inputPath} = itemDefinition + let {schema, inputPath} = itemDefinition let fieldOuputVar = b->B.useWithTypeFilter( - ~struct, + ~schema, ~input=`${inputVar}${inputPath}`, ~path=path->Path.concat(inputPath), ) - let isAsyncField = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let isAsyncField = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) if isAsyncField { // TODO: Ensure that it's not a var, but inlined asyncOutputVars->Js.Array2.push(fieldOuputVar)->ignore @@ -1865,7 +1865,7 @@ module Object = { @as("n") fieldNames: array, @as("h") - fields: Js.Dict.t>, + fields: Js.Dict.t>, @as("d") itemDefinitionsSet: Stdlib.Set.t, // Public API for JS/TS users. @@ -1886,9 +1886,9 @@ module Object = { let itemDefinitionsSet = Stdlib.Set.empty() let field: - type value. (string, struct) => value = - (fieldName, struct) => { - let struct = struct->toUnknown + type value. (string, schema) => value = + (fieldName, schema) => { + let schema = schema->toUnknown let inlinedInputLocation = fieldName->Stdlib.Inlined.Value.fromString if fields->Stdlib.Dict.has(fieldName) { InternalError.panic( @@ -1896,11 +1896,11 @@ module Object = { ) } else { let itemDefinition: itemDefinition = { - struct, + schema, inlinedInputLocation, inputPath: inlinedInputLocation->Path.fromInlinedLocation, } - fields->Js.Dict.set(fieldName, struct) + fields->Js.Dict.set(fieldName, schema) fieldNames->Js.Array2.push(fieldName)->ignore itemDefinitionsSet->Stdlib.Set.add(itemDefinition)->ignore itemDefinition->(Obj.magic: itemDefinition => value) @@ -1911,8 +1911,8 @@ module Object = { let _ = field(tag, literal(asValue)) } - let fieldOr = (fieldName, struct, or) => { - field(fieldName, Option.factory(struct)->Option.getOr(or)) + let fieldOr = (fieldName, schema, or) => { + field(fieldName, Option.factory(schema)->Option.getOr(or)) } { @@ -1941,8 +1941,8 @@ module Object = { ~name=() => `Object({${fieldNames ->Js.Array2.map(fieldName => { - let fieldStruct = fields->Js.Dict.unsafeGet(fieldName) - `${fieldName->Stdlib.Inlined.Value.fromString}: ${fieldStruct.name()}` + let fieldSchema = fields->Js.Dict.unsafeGet(fieldName) + `${fieldName->Stdlib.Inlined.Value.fromString}: ${fieldSchema.name()}` }) ->Js.Array2.joinWith(", ")}})`, ~metadataMap=Metadata.Map.empty, @@ -1956,9 +1956,9 @@ module Object = { ~itemDefinitionsSet, ~definition, ~inputRefinement=noopRefinement, - ~unknownKeysRefinement=(b, ~selfStruct, ~inputVar, ~path) => { + ~unknownKeysRefinement=(b, ~selfSchema, ~inputVar, ~path) => { let withUnknownKeysRefinement = - (selfStruct->classify->Obj.magic)["unknownKeys"] === Strict + (selfSchema->classify->Obj.magic)["unknownKeys"] === Strict switch (withUnknownKeysRefinement, itemDefinitions) { | (true, []) => { let keyVar = b->B.var @@ -1992,7 +1992,7 @@ module Object = { } }, ), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let inputVar = b->B.useInputVar let fieldsCodeRef = ref("") @@ -2013,11 +2013,11 @@ module Object = { ) } else { registeredDefinitions->Stdlib.Set.add(itemDefinition)->ignore - let {inlinedInputLocation, struct} = itemDefinition + let {inlinedInputLocation, schema} = itemDefinition fieldsCodeRef.contents = fieldsCodeRef.contents ++ `${inlinedInputLocation}:${b->B.use( - ~struct, + ~schema, ~input=`${inputVar}${outputPath}`, ~path=path->Path.concat(outputPath), )},` @@ -2056,8 +2056,8 @@ module Object = { for idx in 0 to itemDefinitions->Js.Array2.length - 1 { let itemDefinition = itemDefinitions->Js.Array2.unsafe_get(idx) if registeredDefinitions->Stdlib.Set.has(itemDefinition)->not { - let {struct, inlinedInputLocation} = itemDefinition - switch struct->toLiteral { + let {schema, inlinedInputLocation} = itemDefinition + switch schema->toLiteral { | Some(literal) => fieldsCodeRef.contents = fieldsCodeRef.contents ++ @@ -2077,47 +2077,47 @@ module Object = { ) } - let strip = struct => { - switch struct->classify { + let strip = schema => { + switch schema->classify { | Object({unknownKeys: Strict, fieldNames, fields}) => make( - ~name=struct.name, + ~name=schema.name, ~tagged=Object({unknownKeys: Strip, fieldNames, fields}), - ~parseOperationBuilder=struct.parseOperationBuilder, - ~serializeOperationBuilder=struct.serializeOperationBuilder, - ~maybeTypeFilter=struct.maybeTypeFilter, - ~metadataMap=struct.metadataMap, + ~parseOperationBuilder=schema.parseOperationBuilder, + ~serializeOperationBuilder=schema.serializeOperationBuilder, + ~maybeTypeFilter=schema.maybeTypeFilter, + ~metadataMap=schema.metadataMap, ) - | _ => struct + | _ => schema } } - let strict = struct => { - switch struct->classify { + let strict = schema => { + switch schema->classify { | Object({unknownKeys: Strip, fieldNames, fields}) => make( - ~name=struct.name, + ~name=schema.name, ~tagged=Object({unknownKeys: Strict, fieldNames, fields}), - ~parseOperationBuilder=struct.parseOperationBuilder, - ~serializeOperationBuilder=struct.serializeOperationBuilder, - ~maybeTypeFilter=struct.maybeTypeFilter, - ~metadataMap=struct.metadataMap, + ~parseOperationBuilder=schema.parseOperationBuilder, + ~serializeOperationBuilder=schema.serializeOperationBuilder, + ~maybeTypeFilter=schema.maybeTypeFilter, + ~metadataMap=schema.metadataMap, ) - // TODO: Should it throw for non Object structs? - | _ => struct + // TODO: Should it throw for non Object schemas? + | _ => schema } } } module Never = { - let builder = Builder.make((b, ~selfStruct, ~path) => { + let builder = Builder.make((b, ~selfSchema, ~path) => { let input = b->B.useInput b.code = b.code ++ b->B.raiseWithArg( ~path, input => InvalidType({ - expected: selfStruct, + expected: selfSchema, received: input, }), input, @@ -2125,7 +2125,7 @@ module Never = { input }) - let struct = make( + let schema = make( ~name=primitiveName, ~metadataMap=Metadata.Map.empty, ~tagged=Never, @@ -2136,7 +2136,7 @@ module Never = { } module Unknown = { - let struct = { + let schema = { name: primitiveName, tagged: Unknown, parseOperationBuilder: Builder.noop, @@ -2165,13 +2165,13 @@ module String = { } let metadataId: Metadata.Id.t> = Metadata.Id.make( - ~namespace="rescript-struct", + ~namespace="rescript-schema", ~name="String.refinements", ) } - let refinements = struct => { - switch struct->Metadata.get(~id=Refinement.metadataId) { + let refinements = schema => { + switch schema->Metadata.get(~id=Refinement.metadataId) { | Some(m) => m | None => [] } @@ -2186,7 +2186,7 @@ module String = { let typeFilter = (~inputVar) => `typeof ${inputVar}!=="string"` - let struct = makeWithNoopSerializer( + let schema = makeWithNoopSerializer( ~name=primitiveName, ~metadataMap=Metadata.Map.empty, ~tagged=String, @@ -2194,14 +2194,14 @@ module String = { ~maybeTypeFilter=Some(typeFilter), ) - let min = (struct, length, ~message as maybeMessage=?) => { + let min = (schema, length, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `String must be ${length->Stdlib.Int.unsafeToString} or more characters long` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}.length<${b->B.embed(length)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2211,14 +2211,14 @@ module String = { ) } - let max = (struct, length, ~message as maybeMessage=?) => { + let max = (schema, length, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `String must be ${length->Stdlib.Int.unsafeToString} or fewer characters long` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}.length>${b->B.embed(length)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2228,14 +2228,14 @@ module String = { ) } - let length = (struct, length, ~message as maybeMessage=?) => { + let length = (schema, length, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `String must be exactly ${length->Stdlib.Int.unsafeToString} characters long` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}.length!==${b->B.embed(length)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2245,10 +2245,10 @@ module String = { ) } - let email = (struct, ~message=`Invalid email address`) => { - struct->addRefinement( + let email = (schema, ~message=`Invalid email address`) => { + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(!${b->B.embed(emailRegex)}.test(${inputVar})){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2258,10 +2258,10 @@ module String = { ) } - let uuid = (struct, ~message=`Invalid UUID`) => { - struct->addRefinement( + let uuid = (schema, ~message=`Invalid UUID`) => { + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(!${b->B.embed(uuidRegex)}.test(${inputVar})){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2271,10 +2271,10 @@ module String = { ) } - let cuid = (struct, ~message=`Invalid CUID`) => { - struct->addRefinement( + let cuid = (schema, ~message=`Invalid CUID`) => { + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(!${b->B.embed(cuidRegex)}.test(${inputVar})){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2284,10 +2284,10 @@ module String = { ) } - let url = (struct, ~message=`Invalid url`) => { - struct->addRefinement( + let url = (schema, ~message=`Invalid url`) => { + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `try{new URL(${inputVar})}catch(_){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2297,10 +2297,10 @@ module String = { ) } - let pattern = (struct, re, ~message=`Invalid`) => { - struct->addRefinement( + let pattern = (schema, re, ~message=`Invalid`) => { + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { let reVar = b->B.var `${reVar}=${b->B.embed( re, @@ -2313,16 +2313,16 @@ module String = { ) } - let datetime = (struct, ~message=`Invalid datetime string! Must be UTC`) => { + let datetime = (schema, ~message=`Invalid datetime string! Must be UTC`) => { let refinement = { Refinement.kind: Datetime, message, } - struct + schema ->Metadata.set( ~id=Refinement.metadataId, { - switch struct->Metadata.get(~id=Refinement.metadataId) { + switch schema->Metadata.get(~id=Refinement.metadataId) { | Some(refinements) => refinements->Stdlib.Array.append(refinement) | None => [refinement] } @@ -2339,22 +2339,22 @@ module String = { }) } - let trim = struct => { + let trim = schema => { let transformer = string => string->Js.String2.trim - struct->transform(_ => {parser: transformer, serializer: transformer}) + schema->transform(_ => {parser: transformer, serializer: transformer}) } } module JsonString = { - let factory = struct => { - let struct = struct->toUnknown + let factory = schema => { + let schema = schema->toUnknown try { - struct->validateJsonableStruct(~rootStruct=struct, ~isRoot=true) + schema->validateJsonableSchema(~rootSchema=schema, ~isRoot=true) } catch { | exn => { let _ = exn->InternalError.getOrRethrow InternalError.panic( - `The struct ${struct.name()} passed to S.jsonString is not compatible with JSON`, + `The schema ${schema.name()} passed to S.jsonString is not compatible with JSON`, ) } } @@ -2362,7 +2362,7 @@ module JsonString = { ~name=primitiveName, ~metadataMap=Metadata.Map.empty, ~tagged=String, - ~parseOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~parseOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let input = b->B.useInput let jsonVar = b->B.var b.code = @@ -2373,11 +2373,11 @@ module JsonString = { "t.message", )}}` - b->B.useWithTypeFilter(~struct, ~input=jsonVar, ~path) + b->B.useWithTypeFilter(~schema, ~input=jsonVar, ~path) }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let input = b->B.useInput - `JSON.stringify(${b->B.use(~struct, ~input, ~path)})` + `JSON.stringify(${b->B.use(~schema, ~input, ~path)})` }), ~maybeTypeFilter=Some(String.typeFilter), ) @@ -2387,7 +2387,7 @@ module JsonString = { module Bool = { let typeFilter = (~inputVar) => `typeof ${inputVar}!=="boolean"` - let struct = makeWithNoopSerializer( + let schema = makeWithNoopSerializer( ~name=primitiveName, ~metadataMap=Metadata.Map.empty, ~tagged=Bool, @@ -2408,13 +2408,13 @@ module Int = { } let metadataId: Metadata.Id.t> = Metadata.Id.make( - ~namespace="rescript-struct", + ~namespace="rescript-schema", ~name="Int.refinements", ) } - let refinements = struct => { - switch struct->Metadata.get(~id=Refinement.metadataId) { + let refinements = schema => { + switch schema->Metadata.get(~id=Refinement.metadataId) { | Some(m) => m | None => [] } @@ -2423,7 +2423,7 @@ module Int = { let typeFilter = (~inputVar) => `typeof ${inputVar}!=="number"||${inputVar}>2147483647||${inputVar}<-2147483648||${inputVar}%1!==0` - let struct = makeWithNoopSerializer( + let schema = makeWithNoopSerializer( ~name=primitiveName, ~metadataMap=Metadata.Map.empty, ~tagged=Int, @@ -2431,14 +2431,14 @@ module Int = { ~maybeTypeFilter=Some(typeFilter), ) - let min = (struct, minValue, ~message as maybeMessage=?) => { + let min = (schema, minValue, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `Number must be greater than or equal to ${minValue->Stdlib.Int.unsafeToString}` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}<${b->B.embed(minValue)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2448,14 +2448,14 @@ module Int = { ) } - let max = (struct, maxValue, ~message as maybeMessage=?) => { + let max = (schema, maxValue, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `Number must be lower than or equal to ${maxValue->Stdlib.Int.unsafeToString}` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}>${b->B.embed(maxValue)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2465,10 +2465,10 @@ module Int = { ) } - let port = (struct, ~message="Invalid port") => { - struct->addRefinement( + let port = (schema, ~message="Invalid port") => { + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}<1||${inputVar}>65535){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2490,13 +2490,13 @@ module Float = { } let metadataId: Metadata.Id.t> = Metadata.Id.make( - ~namespace="rescript-struct", + ~namespace="rescript-schema", ~name="Float.refinements", ) } - let refinements = struct => { - switch struct->Metadata.get(~id=Refinement.metadataId) { + let refinements = schema => { + switch schema->Metadata.get(~id=Refinement.metadataId) { | Some(m) => m | None => [] } @@ -2504,7 +2504,7 @@ module Float = { let typeFilter = (~inputVar) => `typeof ${inputVar}!=="number"||Number.isNaN(${inputVar})` - let struct = makeWithNoopSerializer( + let schema = makeWithNoopSerializer( ~name=primitiveName, ~metadataMap=Metadata.Map.empty, ~tagged=Float, @@ -2512,14 +2512,14 @@ module Float = { ~maybeTypeFilter=Some(typeFilter), ) - let min = (struct, minValue, ~message as maybeMessage=?) => { + let min = (schema, minValue, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `Number must be greater than or equal to ${minValue->Stdlib.Float.unsafeToString}` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}<${b->B.embed(minValue)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2529,14 +2529,14 @@ module Float = { ) } - let max = (struct, maxValue, ~message as maybeMessage=?) => { + let max = (schema, maxValue, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `Number must be lower than or equal to ${maxValue->Stdlib.Float.unsafeToString}` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}>${b->B.embed(maxValue)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2559,13 +2559,13 @@ module Array = { } let metadataId: Metadata.Id.t> = Metadata.Id.make( - ~namespace="rescript-struct", + ~namespace="rescript-schema", ~name="Array.refinements", ) } - let refinements = struct => { - switch struct->Metadata.get(~id=Refinement.metadataId) { + let refinements = schema => { + switch schema->Metadata.get(~id=Refinement.metadataId) { | Some(m) => m | None => [] } @@ -2573,13 +2573,13 @@ module Array = { let typeFilter = (~inputVar) => `!Array.isArray(${inputVar})` - let factory = struct => { - let struct = struct->toUnknown + let factory = schema => { + let schema = schema->toUnknown make( ~name=containerName, ~metadataMap=Metadata.Map.empty, - ~tagged=Array(struct), - ~parseOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~tagged=Array(schema), + ~parseOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let inputVar = b->B.useInputVar let iteratorVar = b->B.varWithoutAllocation let outputVar = b->B.var @@ -2593,13 +2593,13 @@ module Array = { ~path, ~dynamicLocationVar=iteratorVar, (b, ~path) => - b->B.useWithTypeFilter(~struct, ~input=`${inputVar}[${iteratorVar}]`, ~path), + b->B.useWithTypeFilter(~schema, ~input=`${inputVar}[${iteratorVar}]`, ~path), ) `${outputVar}.push(${itemOutputVar})` }, )}}` - let isAsync = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let isAsync = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) if isAsync { let asyncOutputVar = b->B.var b.code = b.code ++ `${asyncOutputVar}=()=>Promise.all(${outputVar}.map(t=>t()));` @@ -2608,8 +2608,8 @@ module Array = { outputVar } }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { - if struct.serializeOperationBuilder === Builder.noop { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { + if schema.serializeOperationBuilder === Builder.noop { b->B.useInput } else { let inputVar = b->B.useInputVar @@ -2624,7 +2624,7 @@ module Array = { b->B.withPathPrepend( ~path, ~dynamicLocationVar=iteratorVar, - (b, ~path) => b->B.use(~struct, ~input=`${inputVar}[${iteratorVar}]`, ~path), + (b, ~path) => b->B.use(~schema, ~input=`${inputVar}[${iteratorVar}]`, ~path), ) `${outputVar}.push(${itemOutputVar})` }, @@ -2637,14 +2637,14 @@ module Array = { ) } - let min = (struct, length, ~message as maybeMessage=?) => { + let min = (schema, length, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `Array must be ${length->Stdlib.Int.unsafeToString} or more items long` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}.length<${b->B.embed(length)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2654,14 +2654,14 @@ module Array = { ) } - let max = (struct, length, ~message as maybeMessage=?) => { + let max = (schema, length, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `Array must be ${length->Stdlib.Int.unsafeToString} or fewer items long` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}.length>${b->B.embed(length)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2671,14 +2671,14 @@ module Array = { ) } - let length = (struct, length, ~message as maybeMessage=?) => { + let length = (schema, length, ~message as maybeMessage=?) => { let message = switch maybeMessage { | Some(m) => m | None => `Array must be exactly ${length->Stdlib.Int.unsafeToString} items long` } - struct->addRefinement( + schema->addRefinement( ~metadataId=Refinement.metadataId, - ~refiner=(b, ~inputVar, ~selfStruct as _, ~path) => { + ~refiner=(b, ~inputVar, ~selfSchema as _, ~path) => { `if(${inputVar}.length!==${b->B.embed(length)}){${b->B.fail(~message, ~path)}}` }, ~refinement={ @@ -2690,13 +2690,13 @@ module Array = { } module Dict = { - let factory = struct => { - let struct = struct->toUnknown + let factory = schema => { + let schema = schema->toUnknown make( ~name=containerName, ~metadataMap=Metadata.Map.empty, - ~tagged=Dict(struct), - ~parseOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~tagged=Dict(schema), + ~parseOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let inputVar = b->B.useInputVar let keyVar = b->B.varWithoutAllocation let outputVar = b->B.var @@ -2709,12 +2709,12 @@ module Dict = { ~path, ~dynamicLocationVar=keyVar, (b, ~path) => - b->B.useWithTypeFilter(~struct, ~input=`${inputVar}[${keyVar}]`, ~path), + b->B.useWithTypeFilter(~schema, ~input=`${inputVar}[${keyVar}]`, ~path), ) `${outputVar}[${keyVar}]=${itemOutputVar}` })}}` - let isAsync = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let isAsync = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) if isAsync { let resolveVar = b->B.varWithoutAllocation let rejectVar = b->B.varWithoutAllocation @@ -2729,8 +2729,8 @@ module Dict = { outputVar } }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { - if struct.serializeOperationBuilder === Builder.noop { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { + if schema.serializeOperationBuilder === Builder.noop { b->B.useInput } else { let inputVar = b->B.useInputVar @@ -2744,7 +2744,7 @@ module Dict = { b->B.withPathPrepend( ~path, ~dynamicLocationVar=keyVar, - (b, ~path) => b->B.use(~struct, ~input=`${inputVar}[${keyVar}]`, ~path), + (b, ~path) => b->B.use(~schema, ~input=`${inputVar}[${keyVar}]`, ~path), ) `${outputVar}[${keyVar}]=${itemOutputVar}` @@ -2767,7 +2767,7 @@ module Tuple = { module Ctx = { type t = { @as("s") - structs: array>, + schemas: array>, @as("d") itemDefinitionsSet: Stdlib.Set.t, @as("item") _jsItem: 'value. (int, t<'value>) => 'value, @@ -2777,25 +2777,25 @@ module Tuple = { @inline let make = () => { - let structs = [] + let schemas = [] let itemDefinitionsSet = Stdlib.Set.empty() let item: - type value. (int, struct) => value = - (idx, struct) => { - let struct = struct->toUnknown + type value. (int, schema) => value = + (idx, schema) => { + let schema = schema->toUnknown let inlinedInputLocation = `"${idx->Stdlib.Int.unsafeToString}"` - if structs->Stdlib.Array.has(idx) { + if schemas->Stdlib.Array.has(idx) { InternalError.panic( `The item ${inlinedInputLocation} is defined multiple times. If you want to duplicate the item, use S.transform instead.`, ) } else { let itemDefinition: Object.itemDefinition = { - struct, + schema, inlinedInputLocation, inputPath: inlinedInputLocation->Path.fromInlinedLocation, } - structs->Js.Array2.unsafe_set(idx, struct) + schemas->Js.Array2.unsafe_set(idx, schema) itemDefinitionsSet->Stdlib.Set.add(itemDefinition)->ignore itemDefinition->(Obj.magic: Object.itemDefinition => value) } @@ -2806,7 +2806,7 @@ module Tuple = { } { - structs, + schemas, itemDefinitionsSet, // js/ts methods _jsItem: item, @@ -2821,31 +2821,31 @@ module Tuple = { let factory = definer => { let ctx = Ctx.make() let definition = definer((ctx :> ctx))->(Obj.magic: 'any => Definition.t) - let {itemDefinitionsSet, structs} = ctx - let length = structs->Js.Array2.length + let {itemDefinitionsSet, schemas} = ctx + let length = schemas->Js.Array2.length for idx in 0 to length - 1 { - if structs->Js.Array2.unsafe_get(idx)->Obj.magic->not { - let struct = unit->toUnknown + if schemas->Js.Array2.unsafe_get(idx)->Obj.magic->not { + let schema = unit->toUnknown let inlinedInputLocation = `"${idx->Stdlib.Int.unsafeToString}"` let itemDefinition: Object.itemDefinition = { - struct, + schema, inlinedInputLocation, inputPath: inlinedInputLocation->Path.fromInlinedLocation, } - structs->Js.Array2.unsafe_set(idx, struct) + schemas->Js.Array2.unsafe_set(idx, schema) itemDefinitionsSet->Stdlib.Set.add(itemDefinition)->ignore } } let itemDefinitions = itemDefinitionsSet->Stdlib.Set.toArray make( - ~name=() => `Tuple(${structs->Js.Array2.map(s => s.name())->Js.Array2.joinWith(", ")})`, - ~tagged=Tuple(structs), + ~name=() => `Tuple(${schemas->Js.Array2.map(s => s.name())->Js.Array2.joinWith(", ")})`, + ~tagged=Tuple(schemas), ~parseOperationBuilder=Object.makeParseOperationBuilder( ~itemDefinitions, ~itemDefinitionsSet, ~definition, - ~inputRefinement=(b, ~selfStruct as _, ~inputVar, ~path) => { + ~inputRefinement=(b, ~selfSchema as _, ~inputVar, ~path) => { b.code = b.code ++ `if(${inputVar}.length!==${length->Stdlib.Int.unsafeToString}){${b->B.raiseWithArg( @@ -2859,7 +2859,7 @@ module Tuple = { }, ~unknownKeysRefinement=Object.noopRefinement, ), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let inputVar = b->B.useInputVar let outputVar = b->B.var let registeredDefinitions = Stdlib.Set.empty() @@ -2883,10 +2883,10 @@ module Tuple = { ) } else { registeredDefinitions->Stdlib.Set.add(itemDefinition)->ignore - let {struct, inputPath} = itemDefinition + let {schema, inputPath} = itemDefinition let fieldOuputVar = b->B.use( - ~struct, + ~schema, ~input=`${inputVar}${outputPath}`, ~path=path->Path.concat(outputPath), ) @@ -2926,8 +2926,8 @@ module Tuple = { for idx in 0 to itemDefinitions->Js.Array2.length - 1 { let itemDefinition = itemDefinitions->Js.Array2.unsafe_get(idx) if registeredDefinitions->Stdlib.Set.has(itemDefinition)->not { - let {struct, inlinedInputLocation, inputPath} = itemDefinition - switch struct->toLiteral { + let {schema, inlinedInputLocation, inputPath} = itemDefinition + switch schema->toLiteral { | Some(literal) => b.code = b.code ++ `${outputVar}${inputPath}=${b->B.embed(literal->Literal.value)};` | None => @@ -2948,31 +2948,31 @@ module Tuple = { } module Union = { - let factory = structs => { - let structs: array> = structs->Obj.magic + let factory = schemas => { + let schemas: array> = schemas->Obj.magic - if structs->Js.Array2.length < 2 { - InternalError.panic("A Union struct factory require at least two structs.") + if schemas->Js.Array2.length < 2 { + InternalError.panic("A Union schema factory require at least two schemas.") } make( - ~name=() => `Union(${structs->Js.Array2.map(s => s.name())->Js.Array2.joinWith(", ")})`, + ~name=() => `Union(${schemas->Js.Array2.map(s => s.name())->Js.Array2.joinWith(", ")})`, ~metadataMap=Metadata.Map.empty, - ~tagged=Union(structs), - ~parseOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~tagged=Union(schemas), + ~parseOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let inputVar = b->B.useInputVar - let structs = selfStruct->classify->unsafeGetVariantPayload + let schemas = selfSchema->classify->unsafeGetVariantPayload let isAsyncRef = ref(false) let itemsCode = [] let itemsOutputVar = [] let prevCode = b.code - for idx in 0 to structs->Js.Array2.length - 1 { - let struct = structs->Js.Array2.unsafe_get(idx) + for idx in 0 to schemas->Js.Array2.length - 1 { + let schema = schemas->Js.Array2.unsafe_get(idx) b.code = "" - let itemOutputVar = b->B.useWithTypeFilter(~struct, ~input=inputVar, ~path=Path.empty) - let isAsyncItem = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let itemOutputVar = b->B.useWithTypeFilter(~schema, ~input=inputVar, ~path=Path.empty) + let isAsyncItem = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) if isAsyncItem { isAsyncRef.contents = true } @@ -2988,11 +2988,11 @@ module Union = { let errorCodeRef = ref("") // TODO: Use B.withCatch ??? - for idx in 0 to structs->Js.Array2.length - 1 { - let struct = structs->Js.Array2.unsafe_get(idx) + for idx in 0 to schemas->Js.Array2.length - 1 { + let schema = schemas->Js.Array2.unsafe_get(idx) let code = itemsCode->Js.Array2.unsafe_get(idx) let itemOutputVar = itemsOutputVar->Js.Array2.unsafe_get(idx) - let isAsyncItem = struct.isAsyncParse->(Obj.magic: isAsyncParse => bool) + let isAsyncItem = schema.isAsyncParse->(Obj.magic: isAsyncParse => bool) let errorVar = b->B.varWithoutAllocation @@ -3044,17 +3044,17 @@ module Union = { outputVar } }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let inputVar = b->B.useInputVar - let structs = selfStruct->classify->unsafeGetVariantPayload + let schemas = selfSchema->classify->unsafeGetVariantPayload let outputVar = b->B.var let codeEndRef = ref("") let errorVarsRef = ref("") - for idx in 0 to structs->Js.Array2.length - 1 { - let itemStruct = structs->Js.Array2.unsafe_get(idx) + for idx in 0 to schemas->Js.Array2.length - 1 { + let itemSchema = schemas->Js.Array2.unsafe_get(idx) let errorVar = b->B.varWithoutAllocation errorVarsRef.contents = errorVarsRef.contents ++ errorVar ++ `,` @@ -3062,14 +3062,14 @@ module Union = { b.code ++ `try{${b->B.scope( b => { - let itemOutput = b->B.use(~struct=itemStruct, ~input=inputVar, ~path=Path.empty) - let itemOutput = switch itemStruct.maybeTypeFilter { + let itemOutput = b->B.use(~schema=itemSchema, ~input=inputVar, ~path=Path.empty) + let itemOutput = switch itemSchema.maybeTypeFilter { | Some(typeFilter) => let itemOutputVar = b->B.toVar(itemOutput) b.code = b.code ++ b->B.typeFilterCode( - ~struct=itemStruct, + ~schema=itemSchema, ~typeFilter, ~inputVar=itemOutputVar, ~path=Path.empty, @@ -3100,8 +3100,8 @@ module Union = { } } -let list = struct => { - struct +let list = schema => { + schema ->Array.factory ->transform(_ => { parser: array => array->Belt.List.fromArray, @@ -3114,7 +3114,7 @@ let json = makeWithNoopSerializer( ~tagged=JSON, ~metadataMap=Metadata.Map.empty, ~maybeTypeFilter=None, - ~parseOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~parseOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let rec parse = (input, ~path=path) => { switch input->Stdlib.Type.typeof { | #number if Js.Float.isNaN(input->(Obj.magic: unknown => float))->not => @@ -3154,7 +3154,7 @@ let json = makeWithNoopSerializer( InternalError.raise( ~path, ~code=InvalidType({ - expected: selfStruct, + expected: selfSchema, received: input, }), ~operation=Parsing, @@ -3170,15 +3170,15 @@ let json = makeWithNoopSerializer( type catchCtx<'value> = { @as("e") error: error, @as("i") input: unknown, - @as("s") struct: t<'value>, + @as("s") schema: t<'value>, @as("f") fail: 'a. (string, ~path: Path.t=?) => 'a, @as("w") failWithError: 'a. error => 'a, } -let catch = (struct, getFallbackValue) => { - let struct = struct->toUnknown +let catch = (schema, getFallbackValue) => { + let schema = schema->toUnknown make( - ~name=struct.name, - ~parseOperationBuilder=Builder.make((b, ~selfStruct, ~path) => { + ~name=schema.name, + ~parseOperationBuilder=Builder.make((b, ~selfSchema, ~path) => { let inputVar = b->B.useInputVar b->B.withCatch( ~catch=(b, ~errorVar) => Some( @@ -3186,7 +3186,7 @@ let catch = (struct, getFallbackValue) => { getFallbackValue({ input, error: internalError, - struct: selfStruct->castUnknownStructToAnyStruct, + schema: selfSchema->castUnknownSchemaToAnySchema, failWithError: (error: error) => { InternalError.raise( ~path=path->Path.concat(error.path), @@ -3205,42 +3205,42 @@ let catch = (struct, getFallbackValue) => { )}(${inputVar},${errorVar})`, ), b => { - b->B.useWithTypeFilter(~struct, ~input=inputVar, ~path) + b->B.useWithTypeFilter(~schema, ~input=inputVar, ~path) }, ) }), - ~serializeOperationBuilder=struct.serializeOperationBuilder, - ~tagged=struct.tagged, + ~serializeOperationBuilder=schema.serializeOperationBuilder, + ~tagged=schema.tagged, ~maybeTypeFilter=None, - ~metadataMap=struct.metadataMap, + ~metadataMap=schema.metadataMap, ) } let deprecationMetadataId: Metadata.Id.t = Metadata.Id.make( - ~namespace="rescript-struct", + ~namespace="rescript-schema", ~name="deprecation", ) -let deprecate = (struct, message) => { - struct->Metadata.set(~id=deprecationMetadataId, message) +let deprecate = (schema, message) => { + schema->Metadata.set(~id=deprecationMetadataId, message) } -let deprecation = struct => struct->Metadata.get(~id=deprecationMetadataId) +let deprecation = schema => schema->Metadata.get(~id=deprecationMetadataId) let descriptionMetadataId: Metadata.Id.t = Metadata.Id.make( - ~namespace="rescript-struct", + ~namespace="rescript-schema", ~name="description", ) -let describe = (struct, description) => { - struct->Metadata.set(~id=descriptionMetadataId, description) +let describe = (schema, description) => { + schema->Metadata.set(~id=descriptionMetadataId, description) } -let description = struct => struct->Metadata.get(~id=descriptionMetadataId) +let description = schema => schema->Metadata.get(~id=descriptionMetadataId) module Error = { type class - let class: class = %raw("RescriptStructError") + let class: class = %raw("RescriptSchemaError") let make = InternalError.make @@ -3257,7 +3257,7 @@ module Error = { `Expected ${expected.name()}, received ${received->Literal.classify->Literal.toText}` | InvalidLiteral({expected, received}) => `Expected ${expected->Literal.toText}, received ${received->Literal.classify->Literal.toText}` - | InvalidJsonStruct(struct) => `The struct ${struct.name()} is not compatible with JSON` + | InvalidJsonStruct(schema) => `The schema ${schema.name()} is not compatible with JSON` | InvalidTupleSize({expected, received}) => `Expected Tuple with ${expected->Stdlib.Int.unsafeToString} items, received ${received->Stdlib.Int.unsafeToString}` | InvalidUnion(errors) => { @@ -3294,14 +3294,14 @@ module Error = { } let inline = { - let rec internalInline = (struct, ~variant as maybeVariant=?, ()) => { - let metadataMap = struct.metadataMap->Stdlib.Dict.copy + let rec internalInline = (schema, ~variant as maybeVariant=?, ()) => { + let metadataMap = schema.metadataMap->Stdlib.Dict.copy - let inlinedStruct = switch struct->classify { + let inlinedSchema = switch schema->classify { | Literal(literal) => `S.literal(%raw(\`${literal->Literal.toText}\`))` - | Union(unionStructs) => { + | Union(unionSchemas) => { let variantNamesCounter = Js.Dict.empty() - `S.union([${unionStructs + `S.union([${unionSchemas ->Js.Array2.map(s => { let variantName = s.name() let numberOfVariantNames = switch variantNamesCounter->Js.Dict.get(variantName) { @@ -3324,8 +3324,8 @@ let inline = { | Tuple([s1, s2]) => `S.tuple2(${s1->internalInline()}, ${s2->internalInline()})` | Tuple([s1, s2, s3]) => `S.tuple3(${s1->internalInline()}, ${s2->internalInline()}, ${s3->internalInline()})` - | Tuple(tupleStructs) => - `S.tuple(s => (${tupleStructs + | Tuple(tupleSchemas) => + `S.tuple(s => (${tupleSchemas ->Js.Array2.mapi((s, idx) => `s.item(${idx->Stdlib.Int.unsafeToString}, ${s->internalInline()})` ) @@ -3347,61 +3347,61 @@ let inline = { | Int => `S.int` | Float => `S.float` | Bool => `S.bool` - | Option(struct) => `S.option(${struct->internalInline()})` - | Null(struct) => `S.null(${struct->internalInline()})` + | Option(schema) => `S.option(${schema->internalInline()})` + | Null(schema) => `S.null(${schema->internalInline()})` | Never => `S.never` | Unknown => `S.unknown` - | Array(struct) => `S.array(${struct->internalInline()})` - | Dict(struct) => `S.dict(${struct->internalInline()})` + | Array(schema) => `S.array(${schema->internalInline()})` + | Dict(schema) => `S.dict(${schema->internalInline()})` } - let inlinedStruct = switch struct->Option.default { + let inlinedSchema = switch schema->Option.default { | Some(default) => { metadataMap->Stdlib.Dict.deleteInPlace(Option.defaultMetadataId->Metadata.Id.toKey) switch default { | Value(defaultValue) => - inlinedStruct ++ + inlinedSchema ++ `->S.Option.getOr(%raw(\`${defaultValue->Stdlib.Inlined.Value.stringify}\`))` | Callback(defaultCb) => - inlinedStruct ++ + inlinedSchema ++ `->S.Option.getOrWith(() => %raw(\`${defaultCb()->Stdlib.Inlined.Value.stringify}\`))` } } - | None => inlinedStruct + | None => inlinedSchema } - let inlinedStruct = switch struct->deprecation { + let inlinedSchema = switch schema->deprecation { | Some(message) => { metadataMap->Stdlib.Dict.deleteInPlace(deprecationMetadataId->Metadata.Id.toKey) - inlinedStruct ++ `->S.deprecate(${message->Stdlib.Inlined.Value.fromString})` + inlinedSchema ++ `->S.deprecate(${message->Stdlib.Inlined.Value.fromString})` } - | None => inlinedStruct + | None => inlinedSchema } - let inlinedStruct = switch struct->description { + let inlinedSchema = switch schema->description { | Some(message) => { metadataMap->Stdlib.Dict.deleteInPlace(descriptionMetadataId->Metadata.Id.toKey) - inlinedStruct ++ `->S.describe(${message->Stdlib.Inlined.Value.stringify})` + inlinedSchema ++ `->S.describe(${message->Stdlib.Inlined.Value.stringify})` } - | None => inlinedStruct + | None => inlinedSchema } - let inlinedStruct = switch struct->classify { - | Object({unknownKeys: Strict}) => inlinedStruct ++ `->S.Object.strict` - | _ => inlinedStruct + let inlinedSchema = switch schema->classify { + | Object({unknownKeys: Strict}) => inlinedSchema ++ `->S.Object.strict` + | _ => inlinedSchema } - let inlinedStruct = switch struct->classify { + let inlinedSchema = switch schema->classify { | String | Literal(String(_)) => - switch struct->String.refinements { - | [] => inlinedStruct + switch schema->String.refinements { + | [] => inlinedSchema | refinements => metadataMap->Stdlib.Dict.deleteInPlace(String.Refinement.metadataId->Metadata.Id.toKey) - inlinedStruct ++ + inlinedSchema ++ refinements ->Js.Array2.map(refinement => { switch refinement { @@ -3431,11 +3431,11 @@ let inline = { } | Int => // | Literal(Int(_)) ??? - switch struct->Int.refinements { - | [] => inlinedStruct + switch schema->Int.refinements { + | [] => inlinedSchema | refinements => metadataMap->Stdlib.Dict.deleteInPlace(Int.Refinement.metadataId->Metadata.Id.toKey) - inlinedStruct ++ + inlinedSchema ++ refinements ->Js.Array2.map(refinement => { switch refinement { @@ -3451,11 +3451,11 @@ let inline = { } | Float => // | Literal(Float(_)) ??? - switch struct->Float.refinements { - | [] => inlinedStruct + switch schema->Float.refinements { + | [] => inlinedSchema | refinements => metadataMap->Stdlib.Dict.deleteInPlace(Float.Refinement.metadataId->Metadata.Id.toKey) - inlinedStruct ++ + inlinedSchema ++ refinements ->Js.Array2.map(refinement => { switch refinement { @@ -3469,11 +3469,11 @@ let inline = { } | Array(_) => - switch struct->Array.refinements { - | [] => inlinedStruct + switch schema->Array.refinements { + | [] => inlinedSchema | refinements => metadataMap->Stdlib.Dict.deleteInPlace(Array.Refinement.metadataId->Metadata.Id.toKey) - inlinedStruct ++ + inlinedSchema ++ refinements ->Js.Array2.map(refinement => { switch refinement { @@ -3488,28 +3488,28 @@ let inline = { ->Js.Array2.joinWith("") } - | _ => inlinedStruct + | _ => inlinedSchema } - let inlinedStruct = if metadataMap->Js.Dict.keys->Js.Array2.length !== 0 { + let inlinedSchema = if metadataMap->Js.Dict.keys->Js.Array2.length !== 0 { `{ - let s = ${inlinedStruct} + let s = ${inlinedSchema} let _ = %raw(\`s.m = ${metadataMap->Js.Json.stringifyAny->Belt.Option.getUnsafe}\`) s }` } else { - inlinedStruct + inlinedSchema } - let inlinedStruct = switch maybeVariant { - | Some(variant) => inlinedStruct ++ `->S.variant(v => ${variant}(v))` - | None => inlinedStruct + let inlinedSchema = switch maybeVariant { + | Some(variant) => inlinedSchema ++ `->S.variant(v => ${variant}(v))` + | None => inlinedSchema } - inlinedStruct + inlinedSchema } - struct => { + schema => { // Have it only for the sake of importing Caml_option in a less painfull way // Not related to the function at all if %raw(`false`) { @@ -3519,17 +3519,17 @@ let inline = { } } - struct->toUnknown->internalInline() + schema->toUnknown->internalInline() } } let object = Object.factory -let never = Never.struct -let unknown = Unknown.struct -let string = String.struct -let bool = Bool.struct -let int = Int.struct -let float = Float.struct +let never = Never.schema +let unknown = Unknown.schema +let string = String.schema +let bool = Bool.schema +let int = Int.schema +let float = Float.schema let null = Null.factory let option = Option.factory let array = Array.factory @@ -3559,40 +3559,40 @@ let toJsResult = (result: result<'value, error>): jsResult<'value> => { } } -let js_parse = (struct, data) => { +let js_parse = (schema, data) => { try { Success({ - value: parseAnyOrRaiseWith(data, struct), + value: parseAnyOrRaiseWith(data, schema), }) } catch { | exn => Failure({error: exn->InternalError.getOrRethrow}) } } -let js_parseOrThrow = (struct, data) => { - data->parseAnyOrRaiseWith(struct) +let js_parseOrThrow = (schema, data) => { + data->parseAnyOrRaiseWith(schema) } -let js_parseAsync = (struct, data) => { - data->parseAnyAsyncWith(struct)->Stdlib.Promise.thenResolve(toJsResult) +let js_parseAsync = (schema, data) => { + data->parseAnyAsyncWith(schema)->Stdlib.Promise.thenResolve(toJsResult) } -let js_serialize = (struct, value) => { +let js_serialize = (schema, value) => { try { Success({ - value: serializeToUnknownOrRaiseWith(value, struct), + value: serializeToUnknownOrRaiseWith(value, schema), }) } catch { | exn => Failure({error: exn->InternalError.getOrRethrow}) } } -let js_serializeOrThrow = (struct, value) => { - value->serializeToUnknownOrRaiseWith(struct) +let js_serializeOrThrow = (schema, value) => { + value->serializeToUnknownOrRaiseWith(schema) } -let js_transform = (struct, ~parser as maybeParser=?, ~serializer as maybeSerializer=?) => { - struct->transform(s => { +let js_transform = (schema, ~parser as maybeParser=?, ~serializer as maybeSerializer=?) => { + schema->transform(s => { { parser: ?switch maybeParser { | Some(parser) => Some(v => parser(v, s)) @@ -3606,15 +3606,15 @@ let js_transform = (struct, ~parser as maybeParser=?, ~serializer as maybeSerial }) } -let js_refine = (struct, refiner) => { - struct->refine(s => { +let js_refine = (schema, refiner) => { + schema->refine(s => { v => refiner(v, s) }) } let noop = a => a -let js_asyncParserRefine = (struct, refine) => { - struct->transform(s => { +let js_asyncParserRefine = (schema, refine) => { + schema->transform(s => { { asyncParser: v => () => refine(v, s)->Stdlib.Promise.thenResolve(() => v), serializer: noop, @@ -3622,12 +3622,12 @@ let js_asyncParserRefine = (struct, refine) => { }) } -let js_optional = (struct, maybeOr) => { - let struct = option(struct) +let js_optional = (schema, maybeOr) => { + let schema = option(schema) switch maybeOr { - | Some(or) if Js.typeof(or) === "function" => struct->Option.getOrWith(or->Obj.magic)->Obj.magic - | Some(or) => struct->Option.getOr(or->Obj.magic)->Obj.magic - | None => struct + | Some(or) if Js.typeof(or) === "function" => schema->Option.getOrWith(or->Obj.magic)->Obj.magic + | Some(or) => schema->Option.getOr(or->Obj.magic)->Obj.magic + | None => schema } } @@ -3636,10 +3636,10 @@ let js_tuple = definer => { let definer = definer->(Obj.magic: unknown => Tuple.ctx => 'a) tuple(definer) } else { - let structs = definer->(Obj.magic: unknown => array>) + let schemas = definer->(Obj.magic: unknown => array>) tuple(s => { - structs->Js.Array2.mapi((struct, idx) => { - s.item(idx, struct) + schemas->Js.Array2.mapi((schema, idx) => { + s.item(idx, schema) }) }) } @@ -3671,8 +3671,8 @@ let js_object = definer => { let fieldNames = definer->Js.Dict.keys for idx in 0 to fieldNames->Js.Array2.length - 1 { let fieldName = fieldNames->Js.Array2.unsafe_get(idx) - let struct = definer->Js.Dict.unsafeGet(fieldName) - definition->Js.Dict.set(fieldName, s.field(fieldName, struct)) + let schema = definer->Js.Dict.unsafeGet(fieldName) + definition->Js.Dict.set(fieldName, s.field(fieldName, schema)) } definition }) @@ -3709,21 +3709,21 @@ let js_merge = (s1, s2) => { fieldNames, fields, }), - ~parseOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~parseOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { let inputVar = b->B.useInputVar - let s1Result = b->B.use(~struct=s1, ~input=inputVar, ~path) - let s2Result = b->B.use(~struct=s2, ~input=inputVar, ~path) + let s1Result = b->B.use(~schema=s1, ~input=inputVar, ~path) + let s2Result = b->B.use(~schema=s2, ~input=inputVar, ~path) // TODO: Check that these are objects // TODO: Check that s1Result is not mutating input `Object.assign(${s1Result}, ${s2Result})` }), - ~serializeOperationBuilder=Builder.make((b, ~selfStruct as _, ~path) => { + ~serializeOperationBuilder=Builder.make((b, ~selfSchema as _, ~path) => { b->B.invalidOperation(~path, ~description=`The S.merge serializing is not supported yet`) }), ~maybeTypeFilter=Some(Object.typeFilter), ~metadataMap=Metadata.Map.empty, ) - | _ => InternalError.panic("The merge supports only Object structs.") + | _ => InternalError.panic("The merge supports only Object schemas.") } } diff --git a/src/S_Core.resi b/src/S_Core.resi index 036466d3..04229ecd 100644 --- a/src/S_Core.resi +++ b/src/S_Core.resi @@ -60,18 +60,18 @@ and tagged = | Union(array>) | Dict(t) | JSON -and struct<'value> = t<'value> +and schema<'value> = t<'value> and error = private {operation: operation, code: errorCode, path: Path.t} and errorCode = | OperationFailed(string) | InvalidOperation({description: string}) - | InvalidType({expected: struct, received: unknown}) + | InvalidType({expected: schema, received: unknown}) | InvalidLiteral({expected: Literal.t, received: unknown}) | InvalidTupleSize({expected: int, received: int}) | ExcessField(string) | InvalidUnion(array) | UnexpectedAsync - | InvalidJsonStruct(struct) + | InvalidJsonStruct(schema) and operation = | Parsing | Serializing @@ -79,7 +79,7 @@ and unknownKeys = Strip | Strict type exn += private Raised(error) type effectCtx<'value> = { - struct: t<'value>, + schema: t<'value>, fail: 'a. (string, ~path: Path.t=?) => 'a, failWithError: 'a. error => 'a, } @@ -119,7 +119,7 @@ let union: array> => t<'value> type catchCtx<'value> = { @as("e") error: error, @as("i") input: unknown, - @as("s") struct: t<'value>, + @as("s") schema: t<'value>, @as("f") fail: 'a. (string, ~path: Path.t=?) => 'a, @as("w") failWithError: 'a. error => 'a, }