Compare commits

..

2 Commits

Author SHA1 Message Date
Julien Valverdé
07e1eabcf1 0.1.3 (#4)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/zod-schema-class/pulls/4
2024-03-24 22:24:25 +01:00
Julien Valverdé
2e09d9a0e0 0.1.2 (#3)
All checks were successful
continuous-integration/drone/push Build is passing
Co-authored-by: Julien Valverdé <julien.valverde@mailo.com>
Reviewed-on: https://git.jvalver.de/Thilawyn/zod-schema-class/pulls/3
2024-03-11 19:44:21 +01:00
40 changed files with 841 additions and 1229 deletions

View File

@@ -16,8 +16,8 @@ local lint_step = {
local build_step = { local build_step = {
name: "build", name: "build",
image: bun_image, image: node_image,
commands: ["bun run build"], commands: ["npm run build"],
}; };
local pack_step = { local pack_step = {

View File

@@ -1,3 +1,3 @@
# schemable-class # zod-schema-class
Create TypeScript classes out of Zod schemas Create TypeScript classes out of Zod schemas

BIN
bun.lockb

Binary file not shown.

View File

@@ -1,6 +1,6 @@
{ {
"name": "@thilawyn/schemable-class", "name": "@thilawyn/zod-schema-class",
"version": "0.1.2", "version": "0.1.3",
"type": "module", "type": "module",
"publishConfig": { "publishConfig": {
"registry": "https://git.jvalver.de/api/packages/thilawyn/npm/" "registry": "https://git.jvalver.de/api/packages/thilawyn/npm/"
@@ -8,65 +8,59 @@
"files": [ "files": [
"./dist" "./dist"
], ],
"types": "./dist/lib.d.ts",
"exports": { "exports": {
".": { ".": {
"import": { "import": {
"types": "./dist/schemable.d.mts", "types": "./dist/lib.d.ts",
"default": "./dist/schemable.mjs" "default": "./dist/lib.js"
}, },
"require": { "require": {
"types": "./dist/schemable.d.cts", "types": "./dist/lib.d.cts",
"default": "./dist/schemable.cjs" "default": "./dist/lib.cjs"
} }
}, },
"./jsonifiable": { "./schema": {
"import": { "import": {
"types": "./dist/jsonifiable.d.mts", "types": "./dist/schema/lib.d.ts",
"default": "./dist/jsonifiable.mjs" "default": "./dist/schema/lib.js"
}, },
"require": { "require": {
"types": "./dist/jsonifiable.d.cts", "types": "./dist/schema/lib.d.cts",
"default": "./dist/jsonifiable.cjs" "default": "./dist/schema/lib.cjs"
}
},
"./observable": {
"import": {
"types": "./dist/observable.d.mts",
"default": "./dist/observable.mjs"
},
"require": {
"types": "./dist/observable.d.cts",
"default": "./dist/observable.cjs"
} }
} }
}, },
"scripts": { "scripts": {
"build": "rollup -c rollup.config.ts", "build": "tsup",
"lint:tsc": "tsc --noEmit", "lint:tsc": "tsc --noEmit",
"clean:cache": "rm -f tsconfig.tsbuildinfo", "clean:cache": "rm -f tsconfig.tsbuildinfo",
"clean:dist": "rm -rf dist", "clean:dist": "rm -rf dist",
"clean:node": "rm -rf node_modules" "clean:node": "rm -rf node_modules"
}, },
"dependencies": { "dependencies": {
"@thilawyn/traitify-ts": "^0.1.13", "@thilawyn/traitify-ts": "^0.1.19",
"decimal.js": "^10.4.3",
"effect": "^2.4.0",
"lodash-es": "^4.17.21", "lodash-es": "^4.17.21",
"mobx": "^6.12.0", "type-fest": "^4.14.0",
"type-fest": "^4.10.3",
"zod": "^3.22.4" "zod": "^3.22.4"
}, },
"peerDependencies": {
"mobx": "^6.12.1",
"decimal.js": "^10.4.3",
"effect": "^2.4.11"
},
"peerDependenciesMeta": {
"mobx": { "optional": true },
"decimal.js": { "optional": true },
"effect": { "optional": true }
},
"devDependencies": { "devDependencies": {
"@rollup/plugin-node-resolve": "^15.2.3",
"@types/lodash-es": "^4.17.12", "@types/lodash-es": "^4.17.12",
"bun-types": "latest", "bun-types": "latest",
"npm-check-updates": "^16.14.15", "npm-check-updates": "^16.14.17",
"npm-sort": "^0.0.4", "npm-sort": "^0.0.4",
"rollup": "^4.12.0", "tsup": "^8.0.2",
"rollup-plugin-cleanup": "^3.2.1",
"rollup-plugin-ts": "^3.4.5",
"ts-functional-pipe": "^3.1.2",
"tsx": "^4.7.1", "tsx": "^4.7.1",
"typescript": "^5.3.3" "typescript": "^5.4.3"
} }
} }

View File

@@ -1,44 +0,0 @@
import { nodeResolve } from "@rollup/plugin-node-resolve"
import { defineConfig } from "rollup"
import cleanup from "rollup-plugin-cleanup"
import ts from "rollup-plugin-ts"
import pkg from "./package.json" assert { type: "json" }
export const createBundleConfig = (
input: string,
name: keyof typeof pkg.exports,
) =>
defineConfig({
input,
output: [
{
file: pkg.exports[name].import.default,
format: "esm",
},
{
file: pkg.exports[name].require.default,
format: "cjs",
},
],
external: id => !/^[./]/.test(id),
plugins: [
nodeResolve(),
ts(),
cleanup({
comments: "jsdoc",
extensions: ["ts"],
}),
],
})
export default [
createBundleConfig("src/index.ts", "."),
createBundleConfig("src/jsonifiable/index.ts", "./jsonifiable"),
createBundleConfig("src/observable/index.ts", "./observable"),
]

View File

@@ -0,0 +1,56 @@
import { TraitInstance, TraitStaticMembers, expression } from "@thilawyn/traitify-ts"
import { AbstractClass } from "type-fest"
import { z } from "zod"
import { ZodSchemaObject, ZodSchemaObjectTrait } from "./traits/ZodSchemaObject"
import { Extend, StaticMembers } from "./util"
export function ExtendZodSchemaClass<
Self extends (
AbstractClass<
Values & TraitInstance<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>,
[values: Values]
> &
TraitStaticMembers<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>
),
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
ExtendedT extends z.ZodRawShape,
ExtendedCatchall extends z.ZodTypeAny,
ExtendedValues extends Values,
ExtendedPartialValues extends Partial<ExtendedValues>,
>(
class_: Self | (
AbstractClass<
Values & TraitInstance<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>,
[values: Values]
> &
TraitStaticMembers<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>
),
schemaWithDefaults: (
schemaWithDefaults: z.ZodObject<T, "strip", Catchall, Values, PartialValues>
) => z.ZodObject<ExtendedT, "strip", ExtendedCatchall, ExtendedValues, ExtendedPartialValues>,
) {
return expression
.extends(
class_ as (
AbstractClass<
Omit<
Extend<[InstanceType<Self>, ExtendedValues]>,
keyof TraitInstance<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>
>,
[values: ExtendedValues]
> &
Omit<
StaticMembers<Self>,
keyof TraitStaticMembers<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>
>
)
)
.expresses(ZodSchemaObject(schemaWithDefaults((class_ as Self).schemaWithDefaults)))
}

View File

@@ -0,0 +1,42 @@
import { expression } from "@thilawyn/traitify-ts"
import { Class, Jsonifiable } from "type-fest"
import { z } from "zod"
import { JsonifiedZodSchemaObject, OfClass, OfClassInstance } from "./traits/JsonifiedZodSchemaObject"
export function JsonifiedZodSchemaClass<
Of extends OfClass<OfInstance, T, Catchall, Values, PartialValues>,
OfInstance extends OfClassInstance<T, Catchall, Values, PartialValues>,
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
JsonifyT extends z.ZodRawShape,
JsonifyCatchall extends z.ZodTypeAny,
DejsonifyT extends z.ZodRawShape,
DejsonifyCatchall extends z.ZodTypeAny,
JsonifiedValues extends object & Jsonifiable,
>(
of: Of | OfClass<OfInstance, T, Catchall, Values, PartialValues>,
props: {
jsonifySchema: (
schema: typeof of.schema
) => z.ZodObject<JsonifyT, "strip", JsonifyCatchall, JsonifiedValues, Values>,
dejsonifySchema: (
schema: typeof of.schema
) => z.ZodObject<DejsonifyT, "strip", DejsonifyCatchall, Values, JsonifiedValues>,
},
) {
return expression
.extends(
class JsonifiedZodSchemaObjectConstructor {
constructor(values: JsonifiedValues) {
Object.assign(this, values)
}
} as Class<JsonifiedValues, [values: JsonifiedValues]>
)
.expresses(JsonifiedZodSchemaObject(of as Of, props))
}

24
src/ZodSchemaClass.ts Normal file
View File

@@ -0,0 +1,24 @@
import { expression } from "@thilawyn/traitify-ts"
import { Class } from "type-fest"
import { z } from "zod"
import { ZodSchemaObject } from "./traits/ZodSchemaObject"
export function ZodSchemaClass<
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
schemaWithDefaults: z.ZodObject<T, "strip", Catchall, Values, PartialValues>
) {
return expression
.extends(
class ZodSchemaObjectConstructor {
constructor(values: Values) {
Object.assign(this, values)
}
} as Class<Values, [values: Values]>
)
.expresses(ZodSchemaObject(schemaWithDefaults))
}

View File

@@ -1,194 +0,0 @@
import { Trait, TraitExpression, TraitExpressionBuilder } from "@thilawyn/traitify-ts"
import { AbstractClass } from "type-fest"
import { JsonifiableObject } from "type-fest/source/jsonifiable"
import { z } from "zod"
import { ZodSchemaAbstractClass } from "../shapes/ZodSchemaClass"
import { DejsonifiableZodSchemaObject } from "../traits/DejsonifiableZodSchemaObject"
import { ExtendableZodSchemaObject } from "../traits/ExtendableZodSchemaObject"
import { InstantiableZodSchemaObject } from "../traits/InstantiableZodSchemaObject"
import { JsonifiableZodSchemaObject } from "../traits/JsonifiableZodSchemaObject"
import { ZodSchemaObjectInstantiationSchemas } from "../traits/ZodSchemaObjectInstantiationSchemas"
import { StaticMembers } from "../util"
export class ZodSchemaClassBuilder<
Superclass extends AbstractClass<object>,
const Traits extends readonly Trait<any, any, any, any>[],
>
extends TraitExpressionBuilder<Superclass, Traits> {
declare ["constructor"]: typeof ZodSchemaClassBuilder
schema<
Super extends AbstractClass<object, []> & { schema?: never, schemaWithDefaultValues?: never },
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
this: ZodSchemaClassBuilder<Super, Traits>,
props: {
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
schemaWithDefaultValues: (
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
) => z.ZodObject<SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>
},
) {
class Schemas extends (this.expressionSuperclass as AbstractClass<object, []>) {
static readonly schema = props.schema
static readonly schemaWithDefaultValues = props.schemaWithDefaultValues(props.schema)
constructor(values: Values) {
super()
Object.assign(this, values)
}
}
return new this.constructor(
Schemas as unknown as (
AbstractClass<
InstanceType<Super> & Values,
ConstructorParameters<typeof Schemas>
> &
StaticMembers<Super> &
StaticMembers<typeof Schemas>
),
[
...this.expressionTraits,
ZodSchemaObjectInstantiationSchemas,
InstantiableZodSchemaObject,
ExtendableZodSchemaObject,
],
)
}
jsonifiable<
Super extends ZodSchemaAbstractClass<Instance, SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>
& { jsonifySchema?: never, dejsonifySchema?: never },
Instance extends Values,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
>(
this: ZodSchemaClassBuilder<
Super | ZodSchemaAbstractClass<Instance, SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>,
Traits
>,
props: {
jsonifySchema: (
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
) => z.ZodObject<JsonifySchemaT, JsonifySchemaUnknownKeys, JsonifySchemaCatchall, JsonifiedValues, Values>
dejsonifySchema: (
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
) => z.ZodObject<DejsonifySchemaT, DejsonifySchemaUnknownKeys, DejsonifySchemaCatchall, Values, JsonifiedValues>
},
) {
const jsonifySchema = props.jsonifySchema(this.expressionSuperclass.schema)
const dejsonifySchema = props.dejsonifySchema(this.expressionSuperclass.schema)
class JsonifiableSchemas extends (this.expressionSuperclass as AbstractClass<object>) {
static readonly jsonifySchema = jsonifySchema
readonly jsonifySchema = jsonifySchema
static readonly dejsonifySchema = dejsonifySchema
readonly dejsonifySchema = dejsonifySchema
}
return new this.constructor(
JsonifiableSchemas as unknown as (
AbstractClass<
Instance & JsonifiableSchemas,
// TODO: for some reason, ConstructorParameters<Super> does not work here. Maybe try to find a fix?
ConstructorParameters<ZodSchemaAbstractClass<Instance, SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>>
> &
StaticMembers<Super> &
StaticMembers<typeof JsonifiableSchemas>
),
[
...this.expressionTraits,
JsonifiableZodSchemaObject,
DejsonifiableZodSchemaObject,
],
)
}
}
export interface ZodSchemaClassBuilder<
Superclass extends AbstractClass<object>,
Traits extends readonly Trait<any, any, any, any>[],
> {
extends<
Super extends AbstractClass<object>
>(
// \/ Ensures `extends` can only be called once at the beginning
this: ZodSchemaClassBuilder<typeof TraitExpression.NullSuperclass, Traits>,
superclass: Super,
): ZodSchemaClassBuilder<Super, Traits>
expresses<
const T extends readonly Trait<
TraitExpression<
typeof TraitExpression.NullSuperclass,
readonly Trait<any, any, any, any>[]
>,
any,
any,
any
>[]
>(
...traits: T
): ZodSchemaClassBuilder<
Superclass,
TraitExpressionBuilder.ExpressesReturnTypeTraits<Traits, T>
>
expressesFirst<
const T extends readonly Trait<
TraitExpression<
typeof TraitExpression.NullSuperclass,
readonly Trait<any, any, any, any>[]
>,
any,
any,
any
>[]
>(
...traits: T
): ZodSchemaClassBuilder<
Superclass,
TraitExpressionBuilder.ExpressesFirstReturnTypeTraits<Traits, T>
>
}
export const zodSchemaClass = new ZodSchemaClassBuilder(TraitExpression.NullSuperclass, [])

View File

@@ -1,196 +0,0 @@
import { expression } from "@thilawyn/traitify-ts"
import { AbstractClass, Simplify } from "type-fest"
import { JsonifiableObject } from "type-fest/source/jsonifiable"
import { z } from "zod"
import { JsonifiableZodSchemaAbstractClass } from "../shapes/JsonifiableZodSchemaClass"
import { ZodSchemaAbstractClass } from "../shapes/ZodSchemaClass"
import { Extend, Override, StaticMembers } from "../util"
export class ZodSchemaClassExtender<
Superclass extends AbstractClass<object>,
Subclass extends AbstractClass<object>,
> {
declare ["constructor"]: typeof ZodSchemaClassExtender
constructor(
readonly superclass: Superclass,
readonly subclass: Subclass,
) {}
schema<
Super extends ZodSchemaAbstractClass<any, SuperSchemaT, SuperSchemaUnknownKeys, SuperSchemaCatchall, SuperValues, SuperDefaultValues>,
SuperSchemaT extends z.ZodRawShape,
SuperSchemaUnknownKeys extends z.UnknownKeysParam,
SuperSchemaCatchall extends z.ZodTypeAny,
SuperValues extends object,
SuperDefaultValues extends Partial<SuperValues>,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
Values extends SuperValues,
DefaultValues extends Partial<Values>,
>(
this: ZodSchemaClassExtender<
Super | ZodSchemaAbstractClass<any, SuperSchemaT, SuperSchemaUnknownKeys, SuperSchemaCatchall, SuperValues, SuperDefaultValues>,
any
>,
props: {
schema: (schema: Super["schema"]) => z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
defaultValues: (defaultValues: SuperDefaultValues) => DefaultValues
},
) {
const schema = props.schema(this.superclass.schema)
const defaultValues = props.defaultValues(this.superclass.defaultValues)
class Schemas extends (this.superclass as AbstractClass<object, any[]>) {
static readonly schema = schema
static readonly defaultValues = defaultValues
}
return new this.constructor(
this.superclass as Super,
Schemas as unknown as AbstractClass<
Simplify<
Extend<[InstanceType<Super>, Values]>
>,
[values: Values]
> &
Simplify<
Override<[
StaticMembers<Super>,
StaticMembers<typeof Schemas>,
]>
>
)
}
jsonifiable<
/** Superclass jsonifiable schemas */
Super extends JsonifiableZodSchemaAbstractClass<
any,
SuperJsonifySchemaT,
SuperJsonifySchemaUnknownKeys,
SuperJsonifySchemaCatchall,
SuperDejsonifySchemaT,
SuperDejsonifySchemaUnknownKeys,
SuperDejsonifySchemaCatchall,
SuperJsonifiedValues,
SuperValues
>,
SuperJsonifySchemaT extends z.ZodRawShape,
SuperJsonifySchemaUnknownKeys extends z.UnknownKeysParam,
SuperJsonifySchemaCatchall extends z.ZodTypeAny,
SuperDejsonifySchemaT extends z.ZodRawShape,
SuperDejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
SuperDejsonifySchemaCatchall extends z.ZodTypeAny,
SuperJsonifiedValues extends JsonifiableObject,
SuperValues extends object,
/** New schemas */
Self extends ZodSchemaAbstractClass<any, SelfSchemaT, SelfSchemaUnknownKeys, SelfSchemaCatchall, SelfValues, SelfDefaultValues>,
SelfSchemaT extends z.ZodRawShape,
SelfSchemaUnknownKeys extends z.UnknownKeysParam,
SelfSchemaCatchall extends z.ZodTypeAny,
SelfValues extends object,
SelfDefaultValues extends Partial<SelfValues>,
/* New jsonifiable schemas */
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends SuperJsonifiedValues,
Values extends SelfValues,
>(
this: ZodSchemaClassExtender<
Super | JsonifiableZodSchemaAbstractClass<
any,
SuperJsonifySchemaT,
SuperJsonifySchemaUnknownKeys,
SuperJsonifySchemaCatchall,
SuperDejsonifySchemaT,
SuperDejsonifySchemaUnknownKeys,
SuperDejsonifySchemaCatchall,
SuperJsonifiedValues,
SuperValues
>,
Self | ZodSchemaAbstractClass<any, SelfSchemaT, SelfSchemaUnknownKeys, SelfSchemaCatchall, SelfValues, SelfDefaultValues>
>,
props: {
jsonifySchema: (
schema: Self["schema"],
jsonifySchema: Super["jsonifySchema"],
) => z.ZodObject<JsonifySchemaT, JsonifySchemaUnknownKeys, JsonifySchemaCatchall, JsonifiedValues, Values>
dejsonifySchema: (
schema: Self["schema"],
dejsonifySchema: Super["dejsonifySchema"],
) => z.ZodObject<DejsonifySchemaT, DejsonifySchemaUnknownKeys, DejsonifySchemaCatchall, Values, JsonifiedValues>
},
) {
const jsonifySchema = props.jsonifySchema(this.subclass.schema, this.superclass.jsonifySchema)
const dejsonifySchema = props.dejsonifySchema(this.subclass.schema, this.superclass.dejsonifySchema)
class JsonifiableSchemas extends (this.subclass as AbstractClass<object>) {
static readonly jsonifySchema = jsonifySchema
readonly jsonifySchema = jsonifySchema
static readonly dejsonifySchema = dejsonifySchema
readonly dejsonifySchema = dejsonifySchema
}
return new this.constructor(
this.superclass as Super,
JsonifiableSchemas as unknown as AbstractClass<
Simplify<
Override<[InstanceType<Self>, JsonifiableSchemas]>
>,
ConstructorParameters<
ZodSchemaAbstractClass<any, SelfSchemaT, SelfSchemaUnknownKeys, SelfSchemaCatchall, SelfValues, SelfDefaultValues>
>
> &
Simplify<
Override<[
StaticMembers<Self>,
StaticMembers<typeof JsonifiableSchemas>,
]>
>,
)
}
toClass() {
return this.subclass
}
toExpressionBuilder() {
return expression.extends(this.subclass)
}
}

View File

@@ -1 +1,6 @@
export { ExtendableZodSchemaObject } from "./traits/ExtendableZodSchemaObject" export { ExtendZodSchemaClass } from "./ExtendZodSchemaClass"
export { JsonifiedZodSchemaClass } from "./JsonifiedZodSchemaClass"
export { ZodSchemaClass } from "./ZodSchemaClass"
export { JsonifiedZodSchemaObject } from "./traits/JsonifiedZodSchemaObject"
export { MobXObservableZodSchemaObject } from "./traits/MobXObservableZodSchemaObject"
export { ZodSchemaObject, ZodSchemaObjectTrait } from "./traits/ZodSchemaObject"

19
src/schema/bigint.ts Normal file
View File

@@ -0,0 +1,19 @@
import { z } from "zod"
type JsonifiedBigIntBrand = "@thilawyn/zod-schema-class/JsonifiedBigInt"
export function jsonify<S extends z.ZodType<bigint>>(schema: S) {
return schema
.transform(v => v.toString())
.brand<JsonifiedBigIntBrand>()
}
export function dejsonify<S extends z.ZodType<bigint>>(schema: S) {
return z
.custom<string & z.BRAND<JsonifiedBigIntBrand>>()
.pipe(z.string())
.pipe(z.coerce.bigint())
.pipe(schema)
}

19
src/schema/date.ts Normal file
View File

@@ -0,0 +1,19 @@
import { z } from "zod"
type JsonifiedDateBrand = "@thilawyn/zod-schema-class/JsonifiedDate"
export function jsonify<S extends z.ZodType<Date>>(schema: S) {
return schema
.transform(v => v.toString())
.brand<JsonifiedDateBrand>()
}
export function dejsonify<S extends z.ZodType<Date>>(schema: S) {
return z
.custom<string & z.BRAND<JsonifiedDateBrand>>()
.pipe(z.string())
.pipe(z.coerce.date())
.pipe(schema)
}

36
src/schema/decimal.ts Normal file
View File

@@ -0,0 +1,36 @@
import Decimal from "decimal.js"
import { z } from "zod"
type JsonifiedDecimalBrand = "@thilawyn/zod-schema-class/JsonifiedDecimal"
export function decimal() {
return z.custom<Decimal>(v => Decimal.isDecimal(v))
}
export module decimal {
export function jsonifyDecimalSchema<S extends z.ZodType<Decimal>>(schema: S) {
return schema
.transform(v => v.toJSON())
.brand<JsonifiedDecimalBrand>()
}
export function dejsonifyDecimalSchema<S extends z.ZodType<Decimal>>(schema: S) {
return z
.custom<string & z.BRAND<JsonifiedDecimalBrand>>()
.pipe(
z
.string()
.transform(v => {
try {
return new Decimal(v)
}
catch (e) {
return v
}
})
)
.pipe(schema)
}
}

View File

@@ -0,0 +1 @@
export { option } from "./option"

146
src/schema/effect/option.ts Normal file
View File

@@ -0,0 +1,146 @@
import { Option } from "effect"
import { identity } from "lodash-es"
import { z } from "zod"
type JsonifiedEffectOptionSomeBrand = "@thilawyn/zod-schema-class/JsonifiedEffectOptionSome"
export function option<InnerS extends z.ZodTypeAny>(schema: InnerS) {
return z.union([option.some(schema), option.none(schema)])
}
export module option {
export type Option<InnerS extends z.ZodTypeAny> = ReturnType<typeof option<InnerS>>
function getSomeSchema<InnerS extends z.ZodTypeAny>(schema: Option<InnerS>): some.Some<InnerS> {
return schema.options[0]
}
function getNoneSchema<InnerS extends z.ZodTypeAny>(schema: Option<InnerS>): none.None<InnerS> {
return schema.options[1]
}
export function jsonify<
InnerS extends z.ZodTypeAny,
JsonifiedInnerS extends z.ZodTypeAny = InnerS,
>(
schema: Option<InnerS>,
jsonifySchema: (schema: InnerS) => JsonifiedInnerS = identity,
) {
return z.union([
some.jsonify(getSomeSchema(schema), jsonifySchema),
none.jsonify(getNoneSchema(schema), jsonifySchema),
])
}
export function dejsonify<
InnerS extends z.ZodTypeAny,
DejsonifiedInnerS extends z.ZodTypeAny = InnerS,
>(
schema: Option<InnerS>,
dejsonifySchema: (schema: InnerS) => DejsonifiedInnerS = identity,
) {
return z.union([
some.dejsonify(getSomeSchema(schema), dejsonifySchema),
none.dejsonify(getNoneSchema(schema), dejsonifySchema),
])
}
export function some<
InnerS extends z.ZodTypeAny
>(
schema: InnerS
) {
return z
.custom<Option.Some<z.output<InnerS>>>(
v => Option.isOption(v) && Option.isSome(v),
"Not an Option.Some",
)
.pipe(z.object({ value: schema }).passthrough())
.transform(v => Option.some<z.output<InnerS>>(v.value))
}
export module some {
export type Some<InnerS extends z.ZodTypeAny> = ReturnType<typeof some<InnerS>>
function getInnerSchema<InnerS extends z.ZodTypeAny>(schema: Some<InnerS>): InnerS {
return schema._def.schema._def.out.shape.value
}
export function jsonify<
InnerS extends z.ZodTypeAny,
JsonifiedInnerS extends z.ZodTypeAny = InnerS,
>(
schema: Some<InnerS>,
jsonifySchema: (schema: InnerS) => JsonifiedInnerS = identity,
) {
return schema
.transform(v => Option.getOrThrow(v))
.pipe(jsonifySchema(getInnerSchema(schema)))
.brand<JsonifiedEffectOptionSomeBrand>()
}
export function dejsonify<
InnerS extends z.ZodTypeAny,
DejsonifiedInnerS extends z.ZodTypeAny = InnerS,
>(
schema: Some<InnerS>,
dejsonifySchema: (schema: InnerS) => DejsonifiedInnerS = identity,
) {
return z
.custom<z.input<DejsonifiedInnerS> & z.BRAND<JsonifiedEffectOptionSomeBrand>>()
.pipe(dejsonifySchema(getInnerSchema(schema)))
.transform(v => Option.some<z.output<DejsonifiedInnerS>>(v))
.pipe(schema)
}
}
export function none<
InnerS extends z.ZodTypeAny | unknown = unknown
>(
_schema?: InnerS
) {
return z.custom<
Option.None<
InnerS extends z.ZodTypeAny
? z.output<InnerS>
: unknown
>
>(
v => Option.isOption(v) && Option.isNone(v),
"Not an Option.None",
)
}
export module none {
export type None<InnerS extends z.ZodTypeAny> = ReturnType<typeof none<InnerS>>
export function jsonify<
InnerS extends z.ZodTypeAny,
JsonifiedInnerS extends z.ZodTypeAny = InnerS,
>(
schema: None<InnerS>,
_jsonifySchema?: (schema: InnerS) => JsonifiedInnerS,
) {
return schema.transform(() => null)
}
export function dejsonify<
InnerS extends z.ZodTypeAny,
DejsonifiedInnerS extends z.ZodTypeAny = InnerS,
>(
schema: None<InnerS>,
_dejsonifySchema?: (schema: InnerS) => DejsonifiedInnerS,
) {
return z
.null()
.transform(() => Option.none<z.output<DejsonifiedInnerS>>())
.pipe(schema)
}
}
}

View File

@@ -1,28 +0,0 @@
import { identity } from "lodash-es"
import { Opaque } from "type-fest"
import { z } from "zod"
export type JsonifiedBigInt = Opaque<string, "@thilawyn/schemable-class/JsonifiedBigInt">
export function jsonifyBigIntSchema<S extends z.ZodBigInt>(schema: S) {
return schema.transform(v => v.toString() as JsonifiedBigInt)
}
export function dejsonifyBigIntSchema<S extends z.ZodBigInt>(schema: S) {
return z
.custom<JsonifiedBigInt>(identity)
.pipe(z
.string()
.transform(v => {
try {
return BigInt(v)
}
catch (e) {
return v
}
})
.pipe(schema)
)
}

View File

@@ -1,28 +0,0 @@
import { identity } from "lodash-es"
import { Opaque } from "type-fest"
import { z } from "zod"
export type JsonifiedDate = Opaque<string, "@thilawyn/schemable-class/JsonifiedDate">
export function jsonifyDateSchema<S extends z.ZodDate>(schema: S) {
return schema.transform(v => v.toString() as JsonifiedDate)
}
export function dejsonifyDateSchema<S extends z.ZodDate>(schema: S) {
return z
.custom<JsonifiedDate>(identity)
.pipe(z
.string()
.transform(v => {
try {
return new Date(v)
}
catch (e) {
return v
}
})
.pipe(schema)
)
}

View File

@@ -1,33 +0,0 @@
import { Decimal } from "decimal.js"
import { identity } from "lodash-es"
import { Opaque } from "type-fest"
import { z } from "zod"
export type JsonifiedDecimal = Opaque<string, "@thilawyn/schemable-class/JsonifiedDecimal">
export function jsonifyDecimalSchema<
S extends z.ZodType<Decimal, z.ZodTypeDef, Decimal>
>(schema: S) {
return schema.transform(v => v.toJSON() as JsonifiedDecimal)
}
export function dejsonifyDecimalSchema<
S extends z.ZodType<Decimal, z.ZodTypeDef, Decimal>
>(schema: S) {
return z
.custom<JsonifiedDecimal>(identity)
.pipe(z
.string()
.transform(v => {
try {
return new Decimal(v)
}
catch (e) {
return v
}
})
.pipe(schema)
)
}

View File

@@ -1,16 +0,0 @@
import { dejsonifyBigIntSchema, jsonifyBigIntSchema } from "./bigint"
import { dejsonifyDateSchema, jsonifyDateSchema } from "./date"
import { dejsonifyDecimalSchema, jsonifyDecimalSchema } from "./decimal"
export const jsonify = {
bigint: jsonifyBigIntSchema,
date: jsonifyDateSchema,
decimal: jsonifyDecimalSchema,
} as const
export const dejsonify = {
bigint: dejsonifyBigIntSchema,
date: dejsonifyDateSchema,
decimal: dejsonifyDecimalSchema,
} as const

12
src/schema/lib.ts Normal file
View File

@@ -0,0 +1,12 @@
import * as bigint from "./bigint"
import * as date from "./date"
import { decimal } from "./decimal"
import * as effect from "./effect"
export const s = {
bigint,
date,
decimal,
effect,
} as const

View File

@@ -1,78 +0,0 @@
import { AbstractClass, Class } from "type-fest"
import { JsonifiableObject } from "type-fest/source/jsonifiable"
import { z } from "zod"
export type JsonifiableZodSchemaClass<
Instance extends Values,
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
> = (
Class<Instance, [values: Values]> &
JsonifiableZodSchemas<
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>
)
export type JsonifiableZodSchemaAbstractClass<
Instance extends Values,
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
> = (
AbstractClass<Instance, [values: Values]> &
JsonifiableZodSchemas<
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>
)
export type JsonifiableZodSchemas<
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
> = {
readonly jsonifySchema: z.ZodObject<JsonifySchemaT, JsonifySchemaUnknownKeys, JsonifySchemaCatchall, JsonifiedValues, Values>
readonly dejsonifySchema: z.ZodObject<DejsonifySchemaT, DejsonifySchemaUnknownKeys, DejsonifySchemaCatchall, Values, JsonifiedValues>
}

View File

@@ -1,55 +0,0 @@
import { AbstractClass, Class } from "type-fest"
import { z } from "zod"
export type ZodSchemaClass<
Instance extends Values,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
> = (
Class<Instance, [values: Values]> &
ZodSchemas<SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>
)
export type ZodSchemaAbstractClass<
Instance extends Values,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
> = (
AbstractClass<Instance, [values: Values]> &
ZodSchemas<SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>
)
export type ZodSchemas<
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
> = {
readonly schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, Values, Values>
readonly schemaWithDefaultValues: z.ZodObject<SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>
}

View File

@@ -1,66 +1,60 @@
import { Implements } from "@thilawyn/traitify-ts" import { Implements } from "@thilawyn/traitify-ts"
import { Option } from "effect"
import { z } from "zod" import { z } from "zod"
import { zodSchemaClass } from "./builders/ZodSchemaClassBuilder" import { ExtendZodSchemaClass } from "./ExtendZodSchemaClass"
import { dejsonify, jsonify } from "./schema/jsonify" import { JsonifiedZodSchemaClass } from "./JsonifiedZodSchemaClass"
import { ZodSchemaClass } from "./ZodSchemaClass"
import { s } from "./schema/lib"
import { MobXObservableZodSchemaObject } from "./traits/MobXObservableZodSchemaObject" import { MobXObservableZodSchemaObject } from "./traits/MobXObservableZodSchemaObject"
const exp = zodSchemaClass const userExp = ZodSchemaClass(
.schema({ z.object({
schema: z.object({
/** User ID */ /** User ID */
id: z.bigint(), id: s.effect.option(z.bigint()).default(Option.none()),
/** Username */ /** Username */
name: z.string(), name: z.string(),
}),
schemaWithDefaultValues: s => s.extend({ /** Role */
id: s.shape.id.default(-1n), role: z.enum(["User", "Moderator", "Admin"]).default("User"),
}),
})
.jsonifiable({
jsonifySchema: s => s.extend({
id: jsonify.bigint(s.shape.id)
}),
dejsonifySchema: s => s.extend({
id: dejsonify.bigint(s.shape.id)
}),
}) })
)
.expresses(MobXObservableZodSchemaObject) .expresses(MobXObservableZodSchemaObject)
.build() .build()
@exp.staticImplements @userExp.staticImplements
class User extends exp.extends implements Implements<typeof exp> {} class User extends userExp.extends implements Implements<typeof userExp> {}
const test = User.schema.extend({ const userInst = User.create({ id: Option.some(1n), name: "User" })
prout: z.string() const userInstEffect = User.createEffect({ id: Option.some(1n), name: "User" })
}).merge(
User.schemaWithDefaultValues
)
const inst = User.create({ id: 1n, name: "User" })
// console.log(inst.name)
const instEffect = User.createEffect({ id: 1n, name: "User" })
// const jsonifiedUser = await inst.jsonifyPromise()
// const AdminUserProto = User.extend()
// .schema({
// schema: s => s.extend({
// name: z.literal("Admin"),
// prout: z.string(),
// }),
// defaultValues: v => ({ ...v, name: "Admin" as const }),
// })
// .jsonifiable({
// jsonifySchema: (s, json) => json.extend({
// prout: s.shape.prout
// })
// })
// class AdminUser extends AdminUserProto.toClass() {} const jsonifiedUserExp = JsonifiedZodSchemaClass(User, {
// const subInst = await AdminUser.createPromise({ id: 2n, prout: "" }) jsonifySchema: schema => schema.extend({
// console.log(subInst) id: s.effect.option.jsonify(schema.shape.id, s.bigint.jsonify)
}),
dejsonifySchema: schema => schema.extend({
id: s.effect.option.dejsonify(schema.shape.id, s.bigint.dejsonify)
}),
}).build()
@jsonifiedUserExp.staticImplements
class JsonifiedUser extends jsonifiedUserExp.extends implements Implements<typeof jsonifiedUserExp> {}
const jsonifiedUserInst = JsonifiedUser.jsonify(userInst)
// console.log(JSON.stringify(jsonifiedUserInst))
console.log(jsonifiedUserInst.dejsonify().id)
const adminUserExp = ExtendZodSchemaClass(User,
schema => schema.extend({
role: z.literal("Admin").default("Admin")
})
).build()
@adminUserExp.staticImplements
class AdminUser extends adminUserExp.extends implements Implements<typeof adminUserExp> {}
const admin = AdminUser.create({ id: Option.some(2n), name: "Admin" })

20
src/tests2.ts Normal file
View File

@@ -0,0 +1,20 @@
import { Option } from "effect"
import { z } from "zod"
import { s } from "./schema/lib"
const schema = z.object({
id: s.effect.option(z.bigint())
})
const jsonifySchema = schema.extend({
id: s.effect.option.jsonify(schema.shape.id, s.bigint.jsonify)
})
const dejsonifySchema = schema.extend({
id: s.effect.option.dejsonify(schema.shape.id, s.bigint.dejsonify)
})
const jsonified = jsonifySchema.parse({ id: Option.some(1n) })
console.log(dejsonifySchema.parse(jsonified))

View File

@@ -1,122 +0,0 @@
import { trait } from "@thilawyn/traitify-ts"
import { Effect } from "effect"
import { JsonifiableObject } from "type-fest/source/jsonifiable"
import { z } from "zod"
import { JsonifiableZodSchemaClass } from "../shapes/JsonifiableZodSchemaClass"
import { parseZodTypeEffect } from "../util"
export const DejsonifiableZodSchemaObject = trait
.implement(Super => class DejsonifiableZodSchemaObject extends Super {
static dejsonify<
Instance extends Values,
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
>(
this: JsonifiableZodSchemaClass<
Instance,
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>,
values: JsonifiedValues,
params?: Partial<z.ParseParams>,
) {
return new this(
this.dejsonifySchema.parse(values, params)
)
}
static async dejsonifyPromise<
Instance extends Values,
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
>(
this: JsonifiableZodSchemaClass<
Instance,
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>,
values: JsonifiedValues,
params?: Partial<z.ParseParams>,
) {
return new this(
await this.dejsonifySchema.parseAsync(values, params)
)
}
static dejsonifyEffect<
Instance extends Values,
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
>(
this: JsonifiableZodSchemaClass<
Instance,
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>,
values: JsonifiedValues,
params?: Partial<z.ParseParams>,
) {
return parseZodTypeEffect(this.dejsonifySchema, values, params).pipe(
Effect.map(values => new this(values)),
)
}
})
.build()

View File

@@ -1,16 +1,51 @@
import { trait } from "@thilawyn/traitify-ts" import { ImplStatic, expression, implStaticThis } from "@thilawyn/traitify-ts"
import { ZodSchemaClassExtender } from "../builders/ZodSchemaClassExtender" import { AbstractClass } from "type-fest"
import { ZodSchemaClass } from "../shapes/ZodSchemaClass" import { z } from "zod"
import { Extend, StaticMembers } from "../util"
import { ZodSchemaObject } from "./ZodSchemaObject"
export const ExtendableZodSchemaObject = trait export const ExtendableZodSchemaObject = <
.implement(Super => class ExtendableZodSchemaObject extends Super { T extends z.ZodRawShape,
static extend< Catchall extends z.ZodTypeAny,
Self extends ZodSchemaClass<any, any, any, any, any, any, any, any, any>, Values extends object,
PartialValues extends Partial<Values>,
>( >(
this: Self schemaWithDefaults: z.ZodObject<T, "strip", Catchall, Values, PartialValues>,
) => expression
.expresses(ZodSchemaObject(schemaWithDefaults))
.build()
.subtrait()
.implement(Super => class ExtendableZodSchemaObjectImpl extends Super {
static extend<
Self extends AbstractClass<Values, [values: Values]>,
ExtendedT extends z.ZodRawShape,
ExtendedCatchall extends z.ZodTypeAny,
ExtendedValues extends Values,
ExtendedPartialValues extends Partial<ExtendedValues>,
>(
this: Self,
schemaWithDefaults: (
schemaWithDefaults: z.ZodObject<T, "strip", Catchall, Values, PartialValues>
) => z.ZodObject<ExtendedT, "strip", ExtendedCatchall, ExtendedValues, ExtendedPartialValues>,
) { ) {
return new ZodSchemaClassExtender(this, this) const t = implStaticThis(ExtendableZodSchemaObjectImpl, this)
return expression
.extends(
t as unknown as (
AbstractClass<
Omit<
Extend<[InstanceType<Self>, ExtendedValues]>,
keyof ExtendableZodSchemaObjectImpl
>,
[values: ExtendedValues]
> &
Omit<StaticMembers<Self>, keyof ImplStatic<typeof ExtendableZodSchemaObjectImpl>>
)
)
.expresses(ExtendableZodSchemaObject(schemaWithDefaults(t.schemaWithDefaults)))
} }
}) })
.build() .build()

View File

@@ -1,90 +0,0 @@
import { TraitStaticMembers, trait } from "@thilawyn/traitify-ts"
import { HasRequiredKeys } from "type-fest"
import { z } from "zod"
import { ZodSchemaClass } from "../shapes/ZodSchemaClass"
import { parseZodTypeEffect } from "../util"
import { ZodSchemaObjectInstantiationSchemas } from "./ZodSchemaObjectInstantiationSchemas"
type ZodSchemaObjectInstantiationSchemasStaticMembers = TraitStaticMembers<typeof ZodSchemaObjectInstantiationSchemas>
type NewZodSchemaInstanceInput<
Values extends object,
DefaultValues extends Partial<Values>,
> = {
[Key in Exclude<keyof Values, keyof DefaultValues>]: Values[Key]
} & {
[Key in keyof DefaultValues]?: Key extends keyof Values
? Values[Key]
: never
}
type ParseParamsArgs = [] | [params: Partial<z.ParseParams>]
type NewZodSchemaInstanceArgs<Input extends object> = (
HasRequiredKeys<Input> extends true
? [values: Input, ...args: ParseParamsArgs]
: [] | [values: Input, ...args: ParseParamsArgs]
)
export const InstantiableZodSchemaObject = trait
.implement(Super => class InstantiableZodSchemaObject extends Super {
static create<
Instance extends Values,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
this: (
ZodSchemaClass<Instance, any, any, any, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues> &
ZodSchemaObjectInstantiationSchemasStaticMembers
),
...[values, params]: NewZodSchemaInstanceArgs<PartialValues>
) {
return this.instantiationSchemaWithDefaultValues().parse(values, params)
}
static async createPromise<
Instance extends Values,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
this: (
ZodSchemaClass<Instance, any, any, any, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues> &
ZodSchemaObjectInstantiationSchemasStaticMembers
),
...[values, params]: NewZodSchemaInstanceArgs<PartialValues>
) {
return this.instantiationSchemaWithDefaultValues().parseAsync(values, params)
}
static createEffect<
Instance extends Values,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
this: (
ZodSchemaClass<Instance, any, any, any, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues> &
ZodSchemaObjectInstantiationSchemasStaticMembers
),
...[values, params]: NewZodSchemaInstanceArgs<PartialValues>
) {
return parseZodTypeEffect(this.instantiationSchemaWithDefaultValues(), values, params)
}
})
.build()

View File

@@ -1,100 +0,0 @@
import { trait } from "@thilawyn/traitify-ts"
import { JsonifiableObject } from "type-fest/source/jsonifiable"
import { z } from "zod"
import { JsonifiableZodSchemas } from "../shapes/JsonifiableZodSchemaClass"
import { parseZodTypeEffect } from "../util"
export const JsonifiableZodSchemaObject = trait
.implement(Super => class JsonifiableZodSchemaObject extends Super {
jsonify<
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
>(
this: Values & JsonifiableZodSchemas<
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>,
params?: Partial<z.ParseParams>,
) {
return this.jsonifySchema.parse(this, params)
}
async jsonifyPromise<
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
>(
this: Values & JsonifiableZodSchemas<
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>,
params?: Partial<z.ParseParams>,
) {
return this.jsonifySchema.parseAsync(this, params)
}
jsonifyEffect<
JsonifySchemaT extends z.ZodRawShape,
JsonifySchemaUnknownKeys extends z.UnknownKeysParam,
JsonifySchemaCatchall extends z.ZodTypeAny,
DejsonifySchemaT extends z.ZodRawShape,
DejsonifySchemaUnknownKeys extends z.UnknownKeysParam,
DejsonifySchemaCatchall extends z.ZodTypeAny,
JsonifiedValues extends JsonifiableObject,
Values extends object,
>(
this: Values & JsonifiableZodSchemas<
JsonifySchemaT,
JsonifySchemaUnknownKeys,
JsonifySchemaCatchall,
DejsonifySchemaT,
DejsonifySchemaUnknownKeys,
DejsonifySchemaCatchall,
JsonifiedValues,
Values
>,
params?: Partial<z.ParseParams>,
) {
return parseZodTypeEffect(this.jsonifySchema, this, params)
}
})
.build()

View File

@@ -0,0 +1,174 @@
import { TraitInstance, TraitStaticMembers, implStaticInstantiableThis, trait } from "@thilawyn/traitify-ts"
import { Class, Jsonifiable } from "type-fest"
import { z } from "zod"
import { parseZodSchemaEffect } from "../util"
import { ZodSchemaObjectTrait } from "./ZodSchemaObject"
export type OfClass<
Instance extends OfClassInstance<T, Catchall, Values, PartialValues>,
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
> = (
Class<Instance, [values: Values]> &
TraitStaticMembers<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>
)
export type OfClassInstance<
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
> = (
Values & TraitInstance<ZodSchemaObjectTrait<T, Catchall, Values, PartialValues>>
)
export const JsonifiedZodSchemaObject = <
Of extends OfClass<OfInstance, T, Catchall, Values, PartialValues>,
OfInstance extends OfClassInstance<T, Catchall, Values, PartialValues>,
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
JsonifyT extends z.ZodRawShape,
JsonifyCatchall extends z.ZodTypeAny,
DejsonifyT extends z.ZodRawShape,
DejsonifyCatchall extends z.ZodTypeAny,
JsonifiedValues extends object & Jsonifiable,
>(
of: Of | OfClass<OfInstance, T, Catchall, Values, PartialValues>,
props: {
jsonifySchema: (
schema: typeof of.schema
) => z.ZodObject<JsonifyT, "strip", JsonifyCatchall, JsonifiedValues, Values>,
dejsonifySchema: (
schema: typeof of.schema
) => z.ZodObject<DejsonifyT, "strip", DejsonifyCatchall, Values, JsonifiedValues>,
},
) => trait
.implement(Super => class JsonifiedZodSchemaObjectImpl extends Super {
declare ["constructor"]: typeof JsonifiedZodSchemaObjectImpl
static readonly of = of as Of
static readonly jsonifySchema = props.jsonifySchema(of.schema)
static readonly dejsonifySchema = props.dejsonifySchema(of.schema)
static pipeSchemaIntoInstance<
Instance extends JsonifiedValues,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaOutput extends JsonifiedValues,
SchemaInput,
>(
this: Class<Instance, [values: JsonifiedValues]>,
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaOutput, SchemaInput>,
) {
return schema.transform(values => new this(values))
}
static jsonify<
Instance extends JsonifiedValues
>(
this: Class<Instance, [values: JsonifiedValues]>,
values: Values,
params?: Partial<z.ParseParams>,
) {
const t = implStaticInstantiableThis(JsonifiedZodSchemaObjectImpl, this)
return t
.pipeSchemaIntoInstance(t.jsonifySchema)
.parse(values, params)
}
static jsonifyPromise<
Instance extends JsonifiedValues
>(
this: Class<Instance, [values: JsonifiedValues]>,
values: Values,
params?: Partial<z.ParseParams>,
) {
const t = implStaticInstantiableThis(JsonifiedZodSchemaObjectImpl, this)
return t
.pipeSchemaIntoInstance(t.jsonifySchema)
.parseAsync(values, params)
}
static jsonifyEffect<
Instance extends JsonifiedValues
>(
this: Class<Instance, [values: JsonifiedValues]>,
values: Values,
params?: Partial<z.ParseParams>,
) {
const t = implStaticInstantiableThis(JsonifiedZodSchemaObjectImpl, this)
return parseZodSchemaEffect(
t.pipeSchemaIntoInstance(t.jsonifySchema),
values,
params,
)
}
static dejsonify(
values: JsonifiedValues,
params?: Partial<z.ParseParams>,
) {
return this.of
.pipeSchemaIntoInstance(this.dejsonifySchema)
.parse(values, params)
}
static dejsonifyPromise(
values: JsonifiedValues,
params?: Partial<z.ParseParams>,
) {
return this.of
.pipeSchemaIntoInstance(this.dejsonifySchema)
.parseAsync(values, params)
}
static dejsonifyEffect(
values: JsonifiedValues,
params?: Partial<z.ParseParams>,
) {
return parseZodSchemaEffect(
this.of.pipeSchemaIntoInstance(this.dejsonifySchema),
values,
params,
)
}
dejsonify(params?: Partial<z.ParseParams>) {
return this.constructor.of.pipeSchemaIntoInstance(
this.constructor.dejsonifySchema
).parse(this, params)
}
dejsonifyPromise(params?: Partial<z.ParseParams>) {
return this.constructor.of.pipeSchemaIntoInstance(
this.constructor.dejsonifySchema
).parseAsync(this, params)
}
dejsonifyEffect(params?: Partial<z.ParseParams>) {
return parseZodSchemaEffect(
this.constructor.of.pipeSchemaIntoInstance(this.constructor.dejsonifySchema),
this,
params,
)
}
})
.build()

View File

@@ -8,13 +8,15 @@ export const MobXObservableZodSchemaObject = trait
.staticAbstract(Super => class extends Super { .staticAbstract(Super => class extends Super {
declare readonly schema: z.ZodObject<z.ZodRawShape, z.UnknownKeysParam, z.ZodTypeAny, object, object> declare readonly schema: z.ZodObject<z.ZodRawShape, z.UnknownKeysParam, z.ZodTypeAny, object, object>
}) })
.implement(Super => class ObservableZodSchemaObject extends Super { .implement(Super => class MobXObservableZodSchemaObjectImpl extends Super {
declare ["constructor"]: typeof MobXObservableZodSchemaObjectImpl
constructor(...args: any[]) { constructor(...args: any[]) {
super(...args) super(...args)
makeObservable(this, makeObservable(this,
mapValues( mapValues(
(this.constructor as typeof ObservableZodSchemaObject).schema.shape, this.constructor.schema.shape,
() => observable, () => observable,
) )
) )

View File

@@ -0,0 +1,115 @@
import { implStaticInstantiableThis, trait } from "@thilawyn/traitify-ts"
import { Class, HasRequiredKeys } from "type-fest"
import { z } from "zod"
import { parseZodSchemaEffect, stripZodObjectDefaults } from "../util"
type CreateArgs<Input extends object> = (
HasRequiredKeys<Input> extends true
? [values: Input, params?: Partial<z.ParseParams>]
: [] | [values: Input, params?: Partial<z.ParseParams>]
)
export const ZodSchemaObject = <
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
schemaWithDefaults: z.ZodObject<T, "strip", Catchall, Values, PartialValues>,
) => trait
.implement(Super => {
class ZodSchemaObjectImpl extends Super {
static readonly schema = stripZodObjectDefaults(schemaWithDefaults)
static readonly schemaWithDefaults = schemaWithDefaults
static pipeSchemaIntoInstance<
Instance extends Values,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaOutput extends Values,
SchemaInput,
>(
this: Class<Instance, [values: Values]>,
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaOutput, SchemaInput>,
) {
return schema.transform(values => new this(values))
}
static pipeInstanceIntoSchema<
Self extends Class<Values, [values: Values]>,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
SchemaOutput,
SchemaInput extends Values,
>(
this: Self,
schema: z.ZodObject<SchemaT, SchemaUnknownKeys, SchemaCatchall, SchemaOutput, SchemaInput>,
) {
return z.instanceof(this).pipe(schema)
}
static create<
Instance extends Values
>(
this: Class<Instance, [values: Values]>,
...[values, params]: CreateArgs<PartialValues>
) {
const t = implStaticInstantiableThis(ZodSchemaObjectImpl, this)
return t
.pipeSchemaIntoInstance(t.schemaWithDefaults)
.parse(values, params)
}
static createPromise<
Instance extends Values
>(
this: Class<Instance, [values: Values]>,
...[values, params]: CreateArgs<PartialValues>
) {
const t = implStaticInstantiableThis(ZodSchemaObjectImpl, this)
return t
.pipeSchemaIntoInstance(t.schemaWithDefaults)
.parseAsync(values, params)
}
static createEffect<
Instance extends Values
>(
this: Class<Instance, [values: Values]>,
...[values, params]: CreateArgs<PartialValues>
) {
const t = implStaticInstantiableThis(ZodSchemaObjectImpl, this)
return parseZodSchemaEffect(
t.pipeSchemaIntoInstance(t.schemaWithDefaults),
values,
params,
)
}
}
return ZodSchemaObjectImpl
})
.build()
export type ZodSchemaObjectTrait<
T extends z.ZodRawShape,
Catchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
> = (
ReturnType<
typeof ZodSchemaObject<T, Catchall, Values, PartialValues>
>
)

View File

@@ -1,37 +0,0 @@
import { trait } from "@thilawyn/traitify-ts"
import { z } from "zod"
import { ZodSchemaClass } from "../shapes/ZodSchemaClass"
export const ZodSchemaObjectInstantiationSchemas = trait
.implement(Super => class ZodSchemaObjectInstantiationSchemas extends Super {
static instantiationSchema<
Instance extends Values,
SchemaT extends z.ZodRawShape,
SchemaUnknownKeys extends z.UnknownKeysParam,
SchemaCatchall extends z.ZodTypeAny,
Values extends object,
>(
this: ZodSchemaClass<Instance, SchemaT, SchemaUnknownKeys, SchemaCatchall, any, any, any, Values, any>,
) {
return this.schema.transform(values => new this(values))
}
static instantiationSchemaWithDefaultValues<
Instance extends Values,
SchemaWithDefaultValuesT extends z.ZodRawShape,
SchemaWithDefaultValuesUnknownKeys extends z.UnknownKeysParam,
SchemaWithDefaultValuesCatchall extends z.ZodTypeAny,
Values extends object,
PartialValues extends Partial<Values>,
>(
this: ZodSchemaClass<Instance, any, any, any, SchemaWithDefaultValuesT, SchemaWithDefaultValuesUnknownKeys, SchemaWithDefaultValuesCatchall, Values, PartialValues>,
) {
return this.schemaWithDefaultValues.transform(values => new this(values))
}
})
.build()

View File

@@ -1,69 +1,6 @@
import { AbstractClass, Class as ConcreteClass } from "type-fest" import { AbstractClass } from "type-fest"
/**
* Represents the possible types of a class.
*/
export type ClassType = "AbstractClass" | "Class"
/**
* Represents a class based on the specified type.
* @template Type - The type of the class ("AbstractClass" or "Class").
* @template T - The type parameter of the class.
* @template Arguments - The type of arguments the class constructor takes.
*/
export type Class<
Type extends ClassType,
T,
Arguments extends unknown[] = any[],
> = (
Type extends "AbstractClass"
? AbstractClass<T, Arguments>
: Type extends "Class"
? ConcreteClass<T, Arguments>
: never
)
/**
* Gets the type of a class (either "Class" or "AbstractClass").
* @template C - The class type to determine.
*/
export type GetClassType<C> = (
C extends ConcreteClass<any>
? "Class"
: C extends AbstractClass<any>
? "AbstractClass"
: never
)
/**
* Represents an array of instances corresponding to the provided classes.
* @template Classes - An array of classes extending AbstractClass.
*/
export type ClassesInstances<Classes extends readonly AbstractClass<any>[]> = (
Classes extends [infer Class, ...infer Rest]
? Class extends AbstractClass<any>
? Rest extends AbstractClass<any>[]
? [InstanceType<Class>, ...ClassesInstances<Rest>]
: never
: never
: []
)
/**
* Represents an intersection of instances of the provided classes.
* @template Classes - An array of classes extending AbstractClass.
*/
export type ClassesInstancesIntersection<Classes extends readonly AbstractClass<any>[]> = (
Classes extends [infer Class, ...infer Rest]
? Class extends AbstractClass<any>
? Rest extends AbstractClass<any>[]
? InstanceType<Class> & ClassesInstancesIntersection<Rest>
: never
: never
: {}
)
/** /**
* Represents the static members of a class. * Represents the static members of a class.
* @template Class - A class extending AbstractClass. * @template Class - A class extending AbstractClass.
@@ -71,31 +8,3 @@ export type ClassesInstancesIntersection<Classes extends readonly AbstractClass<
export type StaticMembers<Class extends AbstractClass<any>> = ( export type StaticMembers<Class extends AbstractClass<any>> = (
Omit<Class, "prototype"> Omit<Class, "prototype">
) )
/**
* Represents an array of static members corresponding to the provided classes.
* @template Classes - An array of classes extending AbstractClass.
*/
export type ClassesStaticMembers<Classes extends readonly AbstractClass<any>[]> = (
Classes extends [infer Class, ...infer Rest]
? Class extends AbstractClass<any>
? Rest extends AbstractClass<any>[]
? [StaticMembers<Class>, ...ClassesStaticMembers<Rest>]
: never
: never
: []
)
/**
* Represents an intersection of static members of the provided classes.
* @template Classes - An array of classes extending AbstractClass.
*/
export type ClassesStaticMembersIntersection<Classes extends readonly AbstractClass<any>[]> = (
Classes extends [infer Class, ...infer Rest]
? Class extends AbstractClass<any>
? Rest extends AbstractClass<any>[]
? StaticMembers<Class> & ClassesStaticMembersIntersection<Rest>
: never
: never
: {}
)

View File

@@ -3,16 +3,13 @@ import { z } from "zod"
/** /**
* Parses a value using a ZodType schema wrapped in an Effect monad. * Parses a value using a Zod schema wrapped in an Effect monad.
* *
* @param schema - The ZodType schema to use for parsing. * @param schema - The Zod schema to use for parsing.
* @param args - The arguments to pass to the `safeParseAsync` method of the schema. * @param args - The arguments to pass to the `safeParseAsync` method of the schema.
* @returns An Effect monad representing the parsing result. * @returns An Effect monad representing the parsing result.
*/ */
export const parseZodTypeEffect = < export const parseZodSchemaEffect = <Output, Input>(
Output,
Input,
>(
schema: z.ZodType<Output, z.ZodTypeDef, Input>, schema: z.ZodType<Output, z.ZodTypeDef, Input>,
...args: Parameters<typeof schema.safeParseAsync> ...args: Parameters<typeof schema.safeParseAsync>
) => pipe( ) => pipe(

View File

@@ -1,4 +1,4 @@
export * from "./class" export * from "./class"
export * from "./effect" export * from "./effect"
export * from "./extend" export * from "./extend"
export * from "./misc" export * from "./zod"

View File

@@ -1,3 +0,0 @@
export function identity<T>(value: T) {
return value
}

25
src/util/zod.ts Normal file
View File

@@ -0,0 +1,25 @@
import { mapValues } from "lodash-es"
import { z } from "zod"
export function stripZodObjectDefaults<
T extends z.ZodRawShape,
UnknownKeys extends z.UnknownKeysParam,
Catchall extends z.ZodTypeAny,
Output,
Input,
>(
schema: z.ZodObject<T, UnknownKeys, Catchall, Output, Input>
) {
return schema.extend(
mapValues(schema.shape, v =>
v instanceof z.ZodDefault
? v.removeDefault()
: v
) as {
[K in keyof T]: T[K] extends z.ZodDefault<z.ZodTypeAny>
? ReturnType<T[K]["removeDefault"]>
: T[K]
}
)
}

View File

@@ -8,7 +8,7 @@
// "allowImportingTsExtensions": true, // "allowImportingTsExtensions": true,
// "noEmit": true, // "noEmit": true,
"declaration": true, "declaration": true,
"composite": true, // "composite": true,
"strict": true, "strict": true,
"downlevelIteration": true, "downlevelIteration": true,
"skipLibCheck": true, "skipLibCheck": true,

11
tsup.config.ts Normal file
View File

@@ -0,0 +1,11 @@
import { defineConfig } from "tsup"
export default defineConfig({
entry: ["src/lib.ts", "src/schema/lib.ts"],
format: ["esm", "cjs"],
dts: true,
splitting: false,
sourcemap: true,
clean: true,
})