@volverjs/form-vue 0.0.9 → 0.0.10-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/utils.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import {
2
2
  type z,
3
3
  type AnyZodObject,
4
+ type ZodTypeAny,
4
5
  ZodDefault,
5
6
  ZodObject,
6
7
  ZodEffects,
@@ -9,44 +10,55 @@ import {
9
10
  } from 'zod'
10
11
 
11
12
  export const defaultObjectBySchema = <
12
- Schema extends AnyZodObject | ZodEffects<AnyZodObject>,
13
+ Schema extends
14
+ | AnyZodObject
15
+ | ZodEffects<AnyZodObject>
16
+ | ZodEffects<ZodEffects<AnyZodObject>>,
13
17
  >(
14
18
  schema: Schema,
15
19
  original: Partial<z.infer<Schema>> = {},
16
20
  ): Partial<z.infer<Schema>> => {
17
- const shape =
18
- schema instanceof ZodEffects ? schema.innerType().shape : schema.shape
19
-
21
+ const getInnerType = <Type extends ZodTypeAny>(
22
+ schema: Type | ZodEffects<Type> | ZodEffects<ZodEffects<Type>>,
23
+ ) => {
24
+ let toReturn = schema
25
+ while (toReturn instanceof ZodEffects) {
26
+ toReturn = toReturn.innerType()
27
+ }
28
+ return toReturn
29
+ }
30
+ const innerType = getInnerType<AnyZodObject>(schema)
20
31
  const unknownKeys =
21
- schema instanceof ZodObject
22
- ? schema._def.unknownKeys === 'passthrough'
32
+ innerType instanceof ZodObject
33
+ ? innerType._def.unknownKeys === 'passthrough'
23
34
  : false
24
35
  return {
25
36
  ...(unknownKeys ? original : {}),
26
37
  ...Object.fromEntries(
27
- Object.entries(shape).map(([key, subSchema]) => {
38
+ Object.entries(innerType.shape).map(([key, subSchema]) => {
28
39
  const originalValue = original[key]
40
+ const innerType = getInnerType(subSchema as ZodTypeAny)
29
41
  let defaultValue = undefined
30
- if (subSchema instanceof ZodDefault) {
31
- defaultValue = subSchema._def.defaultValue()
42
+ if (innerType instanceof ZodDefault) {
43
+ defaultValue = innerType._def.defaultValue()
32
44
  }
33
45
  if (
34
46
  originalValue === null &&
35
- subSchema instanceof ZodNullable
47
+ innerType instanceof ZodNullable
36
48
  ) {
37
49
  return [key, originalValue]
38
50
  }
39
- if (subSchema instanceof ZodSchema) {
40
- const parse = subSchema.safeParse(original[key])
51
+ if (innerType instanceof ZodSchema) {
52
+ const parse = innerType.safeParse(original[key])
41
53
  if (parse.success) {
42
54
  return [key, parse.data ?? defaultValue]
43
55
  }
44
56
  }
45
- if (subSchema instanceof ZodObject) {
57
+ if (innerType instanceof ZodObject) {
46
58
  return [
47
59
  key,
48
60
  defaultObjectBySchema(
49
- subSchema,
61
+ innerType,
50
62
  originalValue && typeof originalValue === 'object'
51
63
  ? originalValue
52
64
  : {},