Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: deserialisation and restructuring #7

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
2 changes: 1 addition & 1 deletion .github/workflows/CI.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ jobs:
steps:
- uses: actions/checkout@v3
- uses: ./.github/actions/node
- run: pnpm build
- run: pnpm run --parallel build

release:
needs: [check-style, lint, test, build]
Expand Down
2 changes: 2 additions & 0 deletions .prettierignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
dist/
pnpm-lock.yaml
1 change: 0 additions & 1 deletion .yarnrc.yml

This file was deleted.

13 changes: 8 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,14 @@
# Zodex

Type-safe (de)?serialization library for [zod](https://zod.dev/). It both serializes and simplifies types, in the following ways:
(De)?serialization library for [zod](https://zod.dev/). It both serializes and simplifies the shape of the schema, in the following ways:

- optional, nullable and default types are inlined into any given types itself

```json
{ "type": "string", "defaultValue": "hi" }
```

- number checks are also inlined into the type itself
- checks are also inlined into the type itself, e.g.

```json
{ "type": "number", "min": 23, "max": 42 }
Expand Down Expand Up @@ -37,9 +37,12 @@ const someZodType = z.discriminatedUnion("id", [
const shape = zerialize(someZodType);
```

Now `typeof shape` will be
If you want to have the refined type for `shape` you can import the `Zerialize` type (this will be the default return of `zerialize` in a feature version, once the types are exhaustive):

```ts
import { Zerialize } from "zodex";

type Shape = Zerialize<typeof someZodType>;
type Shape = {
type: "discriminatedUnion";
discriminator: "id";
Expand Down Expand Up @@ -79,13 +82,13 @@ options:

## Roadmap

- deserialization (WIP lives on branch [dezerial](https://github.com/commonbaseapp/zodex/tree/dezerial), could use some help from TypeScript heroes)
- missing checks
- **number:** gte, lte, positive, nonnegative, negative, nonpositive
- **bigInt:** same as number
- **date**: min, max
- **set**: size
- custom error messages are not included
- return refined types for `zerialize` and `dezerialize`
- missing custom error messages

## Caveats

Expand Down
63 changes: 19 additions & 44 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,56 +1,31 @@
{
"name": "zodex",
"version": "0.0.0-dev",
"description": "Type-safe (de)serialization for Zod",
"main": "dist/index.js",
"types": "dist/index.d.ts",
"keywords": [
"zod",
"serialization",
"deserialization",
"reflection"
],
"author": "Gregor Weber<mail@dflate.io>",
"license": "MIT",
"private": true,
"scripts": {
"prepare": "husky install",
"check-style": "prettier --check src",
"lint": "eslint src/**",
"test": "vitest",
"build": "rm -rf dist && tsc",
"prepublish": "pnpm run build"
},
"peerDependencies": {
"@types/react": "^18.x",
"react": "^18.x",
"zod": "^3.x"
},
"dependencies": {
"react": "18.2.0",
"type-fest": "3.7.1",
"zod": "3.21.4"
"check-style": "prettier --check .",
"lint": "eslint .",
"test": "vitest"
},
"devDependencies": {
"@commitlint/cli": "17.5.1",
"@commitlint/config-conventional": "17.4.4",
"@types/react": "18.0.31",
"@typescript-eslint/eslint-plugin": "5.57.0",
"@typescript-eslint/parser": "5.57.0",
"esbuild": "0.17.14",
"eslint": "8.37.0",
"@commitlint/cli": "17.6.3",
"@commitlint/config-conventional": "17.6.3",
"@types/react": "18.2.6",
"@typescript-eslint/eslint-plugin": "5.59.2",
"@typescript-eslint/parser": "5.59.2",
"esbuild": "0.17.18",
"eslint": "8.40.0",
"eslint-config-prettier": "8.8.0",
"husky": "8.0.3",
"lint-staged": "13.2.0",
"prettier": "2.8.7",
"typescript": "5.0.2",
"vitest": "0.29.8"
"lint-staged": "13.2.2",
"prettier": "2.8.8",
"semantic-release": "^21.0.2",
"semantic-release-monorepo": "^7.0.5",
"typescript": "5.0.4",
"vitest": "0.31.0"
},
"packageManager": "pnpm@8.1.0",
"files": [
"dist/*"
],
"packageManager": "pnpm@8.4.0",
"lint-staged": {
"*.ts": "eslint --cache --fix src/**",
"*.ts": "eslint --cache --fix",
"*.{ts,js,json,md}": "prettier --write"
}
}
259 changes: 259 additions & 0 deletions packages/core/dezerialize.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,259 @@
import { z } from "zod";
import {
SzOptional,
SzNullable,
SzDefault,
SzLiteral,
SzArray,
SzObject,
SzUnion,
SzDiscriminatedUnion,
SzIntersection,
SzTuple,
SzRecord,
SzMap,
SzSet,
SzFunction,
SzEnum,
SzPromise,
SzType,
SzString,
SzNumber,
SzBoolean,
SzBigInt,
SzNaN,
SzDate,
SzAny,
SzNever,
SzNull,
SzUndefined,
SzUnknown,
SzVoid,
} from "./types";
import { ZodTypes } from "./zod-types";

type DistributiveOmit<T, K extends keyof any> = T extends any
? Omit<T, K>
: never;
type OmitKey<T, K> = DistributiveOmit<T, keyof K>;

// Types must match the exported dezerialize function's implementation
export type Dezerialize<T extends SzType> =
// Modifier types
T extends SzOptional
? Dezerialize<OmitKey<T, SzOptional>> extends infer I
? I extends ZodTypes
? z.ZodOptional<I>
: never
: never
: T extends SzNullable
? Dezerialize<OmitKey<T, SzNullable>> extends infer I
? I extends ZodTypes
? z.ZodNullable<I>
: never
: never
: T extends SzDefault<any>
? Dezerialize<OmitKey<T, SzDefault<any>>> extends infer I
? I extends ZodTypes
? z.ZodDefault<I>
: never
: never // Primitives
: T extends SzString
? z.ZodString
: T extends SzNumber
? z.ZodNumber
: T extends SzBoolean
? z.ZodBoolean
: T extends SzBigInt
? z.ZodBigInt
: T extends SzNaN
? z.ZodNaN
: T extends SzDate
? z.ZodDate
: T extends SzUndefined
? z.ZodUndefined
: T extends SzNull
? z.ZodNull
: T extends SzAny
? z.ZodAny
: T extends SzUnknown
? z.ZodUnknown
: T extends SzNever
? z.ZodNever
: T extends SzVoid
? z.ZodVoid
: T extends SzLiteral<infer Value>
? z.ZodLiteral<Value> // List Collections
: T extends SzTuple<infer _Items>
? z.ZodTuple<any> //DezerializeArray<Items>>
: T extends SzSet<infer Value>
? z.ZodSet<Dezerialize<Value>>
: T extends SzArray<infer Element>
? z.ZodArray<Dezerialize<Element>> // Key/Value Collections
: T extends SzObject<infer Properties>
? z.ZodObject<{
[Property in keyof Properties]: Dezerialize<Properties[Property]>;
}>
: T extends SzRecord<infer Key, infer Value>
? z.ZodRecord<Dezerialize<Key>, Dezerialize<Value>>
: T extends SzMap<infer Key, infer Value>
? z.ZodMap<Dezerialize<Key>, Dezerialize<Value>> // Enum
: T extends SzEnum<infer Values>
? z.ZodEnum<Values> // Union/Intersection
: T extends SzUnion<infer _Options>
? z.ZodUnion<any>
: T extends SzDiscriminatedUnion<infer Discriminator, infer _Options>
? z.ZodDiscriminatedUnion<Discriminator, any>
: T extends SzIntersection<infer L, infer R>
? z.ZodIntersection<Dezerialize<L>, Dezerialize<R>> // Specials
: T extends SzFunction<infer Args, infer Return>
? z.ZodFunction<Dezerialize<Args>, Dezerialize<Return>>
: T extends SzPromise<infer Value>
? z.ZodPromise<Dezerialize<Value>>
: unknown;

type DezerializersMap = {
[T in SzType["type"]]: (shape: Extract<SzType, { type: T }>) => ZodTypes; //Dezerialize<Extract<SzType, { type: T }>>;
};
const dezerializers = {
number: (shape) => {
let n = z.number();
if (shape.min !== undefined) {
n = n.min(shape.min);
}
if (shape.max !== undefined) {
n = n.max(shape.max);
}
if (shape.multipleOf !== undefined) {
n = n.multipleOf(shape.multipleOf);
}
if (shape.int) {
n = n.int();
}
if (shape.finite) {
n = n.finite();
}
return n;
},
string: (shape) => {
let s = z.string();
if (shape.min !== undefined) {
s = s.min(shape.min);
}
if (shape.max !== undefined) {
s = s.max(shape.max);
}
if (shape.length !== undefined) {
s = s.length(shape.length);
}
if (shape.startsWith !== undefined) {
s = s.startsWith(shape.startsWith);
}
if (shape.endsWith !== undefined) {
s = s.endsWith(shape.endsWith);
}
if ("includes" in shape) {
s = s.includes(shape.includes, { position: shape.position });
}
if ("regex" in shape) {
s = s.regex(new RegExp(shape.regex, shape.flags));
}
if ("kind" in shape) {
if (shape.kind == "ip") {
s = s.ip({ version: shape.version });
} else if (shape.kind == "datetime") {
s = s.datetime({ offset: shape.offset, precision: shape.precision });
} else {
s = s[shape.kind]();
}
}

return s;
},
boolean: () => z.boolean(),
nan: () => z.nan(),
bigInt: (shape) => {
let i = z.bigint();
if (shape.min !== undefined) {
i = i.min(shape.min);
}
if (shape.max !== undefined) {
i = i.max(shape.max);
}
if (shape.multipleOf !== undefined) {
i = i.multipleOf(shape.multipleOf);
}
return i;
},
date: () => z.date(),
undefined: () => z.undefined(),
null: () => z.null(),
any: () => z.any(),
unknown: () => z.unknown(),
never: () => z.never(),
void: () => z.void(),

literal: (shape) => z.literal(shape.value),

tuple: ((shape: SzTuple) =>
z.tuple(shape.items.map(dezerialize) as any)) as any,
set: ((shape: SzSet) => z.set(dezerialize(shape.value))) as any,
array: ((shape: SzArray) => z.array(dezerialize(shape.element))) as any,

object: ((shape: SzObject) =>
z.object(
Object.fromEntries(
Object.entries(shape.properties).map(([key, value]) => [
key,
dezerialize(value),
])
)
)) as any,
record: ((shape: SzRecord) =>
z.record(dezerialize(shape.key), dezerialize(shape.value))) as any,
map: ((shape: SzMap<any, any>) =>
z.map(dezerialize(shape.key), dezerialize(shape.value))) as any,

enum: ((shape: SzEnum) => z.enum(shape.values)) as any,

union: ((shape: SzUnion) =>
z.union(shape.options.map(dezerialize) as any)) as any,
discriminatedUnion: ((shape: SzDiscriminatedUnion) =>
z.discriminatedUnion(
shape.discriminator,
shape.options.map(dezerialize) as any
)) as any,
intersection: ((shape: SzIntersection) =>
z.intersection(dezerialize(shape.left), dezerialize(shape.right))) as any,

function: ((shape: SzFunction<any, any>) =>
z.function(
dezerialize(shape.args) as any,
dezerialize(shape.returns)
)) as any,
promise: ((shape: SzPromise) => z.promise(dezerialize(shape.value))) as any,
} satisfies DezerializersMap as DezerializersMap;

// Must match the exported Dezerialize types
// export function dezerialize<T extends SzType>(_shape: T): Dezerialize<T>;
export function dezerialize(shape: SzType): ZodTypes {
if ("isOptional" in shape) {
const { isOptional, ...rest } = shape;
const inner = dezerialize(rest);
return isOptional ? inner.optional() : inner;
}

if ("isNullable" in shape) {
const { isNullable, ...rest } = shape;
const inner = dezerialize(rest);
return isNullable ? inner.nullable() : inner;
}

if ("defaultValue" in shape) {
const { defaultValue, ...rest } = shape;
const inner = dezerialize(rest);
return inner.default(defaultValue);
}

return dezerializers[shape.type](shape as any);
}