* Calculate nesting depth of a Zod schema * Depth = 1 for primitive/object shallow, >1 for nested
(schema: z.ZodTypeAny)
| 179 | * Depth = 1 for primitive/object shallow, >1 for nested |
| 180 | */ |
| 181 | function calculateDepth(schema: z.ZodTypeAny): number { |
| 182 | const unwrapped = unwrapEffects(schema); |
| 183 | const typeName = getSchemaType(unwrapped); |
| 184 | |
| 185 | // Primitives: depth 1 |
| 186 | if (isPrimitiveType(unwrapped)) { |
| 187 | return 1; |
| 188 | } |
| 189 | |
| 190 | // Object: depth = 1 + max(field depth) |
| 191 | if (typeName === 'object') { |
| 192 | const shape = getObjectShape(unwrapped); |
| 193 | let maxChildDepth = 0; |
| 194 | |
| 195 | for (const field of Object.values(shape)) { |
| 196 | const childDepth = calculateDepth(field as z.ZodTypeAny); |
| 197 | maxChildDepth = Math.max(maxChildDepth, childDepth); |
| 198 | } |
| 199 | |
| 200 | return 1 + maxChildDepth; |
| 201 | } |
| 202 | |
| 203 | // Array: depth = element depth |
| 204 | if (typeName === 'array') { |
| 205 | const element = (unwrapped as any)._def.element ?? (unwrapped as any)._def.type; |
| 206 | return calculateDepth(element as z.ZodTypeAny); |
| 207 | } |
| 208 | |
| 209 | // Record: depth = value depth |
| 210 | if (typeName === 'record') { |
| 211 | const value = |
| 212 | (unwrapped as any)._def.valueType ?? |
| 213 | (unwrapped as any)._def.value ?? |
| 214 | (unwrapped as any)._def.keyType; |
| 215 | if (!value) { |
| 216 | return 1; |
| 217 | } |
| 218 | return calculateDepth(value as z.ZodTypeAny); |
| 219 | } |
| 220 | |
| 221 | // Default depth for unknown types |
| 222 | return 1; |
| 223 | } |
| 224 | |
| 225 | /** |
| 226 | * Unwrap optional, nullable, default effects |
no test coverage detected