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 type NewZodSchemaInstanceInput< Values extends object, DefaultValues extends Partial, > = { [Key in Exclude]: Values[Key] } & { [Key in keyof DefaultValues]?: Key extends keyof Values ? Values[Key] : never } type ParseParamsArgs = [] | [params: Partial] type NewZodSchemaInstanceArgs = ( HasRequiredKeys 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, >( this: ( ZodSchemaClass & ZodSchemaObjectInstantiationSchemasStaticMembers ), ...[values, params]: NewZodSchemaInstanceArgs ) { 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, >( this: ( ZodSchemaClass & ZodSchemaObjectInstantiationSchemasStaticMembers ), ...[values, params]: NewZodSchemaInstanceArgs ) { 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, >( this: ( ZodSchemaClass & ZodSchemaObjectInstantiationSchemasStaticMembers ), ...[values, params]: NewZodSchemaInstanceArgs ) { return parseZodTypeEffect(this.instantiationSchemaWithDefaultValues(), values, params) } }) .build()