|
1 | 1 | import { z } from 'zod/v4';
|
2 | 2 | import type { $ZodFunction } from 'zod/v4/core';
|
3 | 3 |
|
| 4 | +// https://zod.dev/v4/changelog?id=zfunction |
| 5 | +// https://github.com/colinhacks/zod/issues/4143#issuecomment-2931729793 |
4 | 6 | // https://github.com/matejchalk/zod2md?tab=readme-ov-file#function-schemas
|
5 |
| -export function convertZodFunctionToSchema<T extends $ZodFunction>(factory: T) { |
| 7 | + |
| 8 | +/** |
| 9 | + * Converts Zod v4 function factory (returned by `z.function`) to Zod schema. |
| 10 | + * |
| 11 | + * Supports asynchronous functions. For synchronous functions, you can use {@link convertSyncZodFunctionToSchema}. |
| 12 | + * |
| 13 | + * @param factory `z.function({ input: [...], output: ... })` |
| 14 | + * @returns Zod schema with compile-time and runtime validations. |
| 15 | + */ |
| 16 | +export function convertAsyncZodFunctionToSchema<T extends $ZodFunction>( |
| 17 | + factory: T, |
| 18 | +) { |
| 19 | + return z |
| 20 | + .custom() |
| 21 | + .transform((arg, ctx) => { |
| 22 | + if (typeof arg !== 'function') { |
| 23 | + ctx.addIssue(`Expected function, received ${typeof arg}`); |
| 24 | + return z.NEVER; |
| 25 | + } |
| 26 | + return factory.implementAsync(arg as Parameters<T['implementAsync']>[0]); |
| 27 | + }) |
| 28 | + .meta({ |
| 29 | + // enables zod2md to include function signature in docs |
| 30 | + $ZodFunction: factory, |
| 31 | + }); |
| 32 | +} |
| 33 | + |
| 34 | +/** |
| 35 | + * Converts Zod v4 function factory (returned by `z.function`) to Zod schema. |
| 36 | + * |
| 37 | + * **IMPORTANT!** Use for synchronous functions only. For asynchronous functions use {@link convertAsyncZodFunctionToSchema}. |
| 38 | + * |
| 39 | + * @throws `Encountered Promise during synchronous parse. Use .parseAsync() instead.` if used with async functions. |
| 40 | + * |
| 41 | + * @param factory `z.function({ input: [...], output: ... })` |
| 42 | + * @returns Zod schema with compile-time and runtime validations. |
| 43 | + */ |
| 44 | +export function convertSyncZodFunctionToSchema<T extends $ZodFunction>( |
| 45 | + factory: T, |
| 46 | +) { |
6 | 47 | return z
|
7 | 48 | .custom()
|
8 | 49 | .transform((arg, ctx) => {
|
|
0 commit comments