From 9f87a0d467424fd9b5c8f77dc61f0cdf9b6b6d5c Mon Sep 17 00:00:00 2001 From: Olsten Larck Date: Thu, 30 Jul 2026 23:31:02 +0000 Subject: [PATCH 1/4] detect async schema markers --- README.md | 2 +- src/index.ts | 36 +++++++++++++++++---- src/types.ts | 16 +++++++++ test/main.test.ts | 36 +++++++++++++++++++++ test/types-testing.test.ts | 66 ++++++++++++++++++++++++++++++++++++++ 5 files changed, 148 insertions(+), 8 deletions(-) diff --git a/README.md b/README.md index d6bc324..1a9db8d 100644 --- a/README.md +++ b/README.md @@ -544,7 +544,7 @@ Zagora is fully async-aware at every level of the system: - **Sync/async Schemas**: Input/output/error validation can be async -> procedure becomes async - **Sync/async Cache**: If any cache method is async -> procedure becomes async -**Important:** Due to StandardSchema limitation, if you provide async schema, the created procedure will be with synchronous signature, and will return a `ZagoraResult` object, instead of `Promise`. That is because we cannot know on type-level whether the schema is async or not. So, make sure you always `await` at procedure callsite when you know the that any part of the schema is async! There is an opened issue in the StandardSchema issue tracker, we will see. +**Important:** Standard Schema does not currently identify async schemas in its type contract. Zagora detects validators whose schema type exposes `async: true` (including Valibot), so those procedures correctly return `Promise` at type level. For validators that do not expose such a marker (including Zod), always `await` when you know any part of the schema is async. Follow [Standard Schema issue #22](https://github.com/standard-schema/standard-schema/issues/22) for the upstream contract. Funnily, ArkType does not support async schemas and it's incredibly fast, so using it you won't have that problem to begin with. diff --git a/src/index.ts b/src/index.ts index 4a8f268..122e82a 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ import type { ConditionalAsync, IsPromise } from "./is-promise"; import type { AnySchema, CacheAdapter, + HasAsyncSchema, InferOutput, InferSchemaInput, InferSchemaInputSafe, @@ -203,7 +204,7 @@ export class Zagora< return new Zagora({ ...this["~zagora"], errorsMap, - }); + }) as any; } env( @@ -259,10 +260,14 @@ export class Zagora< ): TAutoCallable extends true ? ResolvedProcedure< TInputSchema, - ConditionalAsync< - ReturnType, - ZagoraResult, TErrorsMap, any> - > + HasAsyncSchema extends true + ? Promise< + ZagoraResult, TErrorsMap, any> + > + : ConditionalAsync< + ReturnType, + ZagoraResult, TErrorsMap, any> + > > : Zagora< TFn, @@ -318,6 +323,13 @@ export class Zagora< const envVarsMapSchema = zagora.envVarsMapSchema; const baseEnvVars = zagora.envVars; + const isAsyncSchema = (schema: unknown) => + (schema as { async?: boolean } | undefined)?.async === true; + const hasAsyncSchema = + isAsyncSchema(inputSchema) || + isAsyncSchema(outputSchema) || + Object.values(errorsMap || {}).some(isAsyncSchema); + const mergedEnvVars = deepMerge(baseEnvVars || {}, env || {}); // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: -- ok @@ -438,7 +450,13 @@ export class Zagora< TResolvedResult >; - type TResult = ConditionalAsync, Result>; + type TResult = HasAsyncSchema< + TInputSchema, + TOutputSchema, + TErrorsMap + > extends true + ? Promise + : ConditionalAsync, Result>; type TFinalResult = TCache extends { has(key: string): infer A; @@ -454,7 +472,11 @@ export class Zagora< : TResult : TResult; - const procedure = forwardProcedure as TInputSchema extends AnySchema + const procedure = ( + hasAsyncSchema + ? (...args: unknown[]) => Promise.resolve(forwardProcedure(...args)) + : forwardProcedure + ) as TInputSchema extends AnySchema ? InferSchemaInput extends readonly [any, ...any[]] ? SpreadTuple, TFinalResult> : (arg: InferSchemaInput) => TFinalResult diff --git a/src/types.ts b/src/types.ts index 1d2ce33..7abf753 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,6 +12,22 @@ export type Schema = StandardSchemaV1; export type AnySchema = Schema; +// TEST: with expect-type +export type IsAsyncSchema = T extends { readonly async: true } + ? true + : false; + +type ErrorSchemas = T extends Record ? T[keyof T] : never; + +// TEST: with expect-type +export type HasAsyncSchema = + true extends + | IsAsyncSchema + | IsAsyncSchema + | IsAsyncSchema> + ? true + : false; + export type SchemaIssue = StandardSchemaV1.Issue; export type InferSchemaOutput = T extends StandardSchemaV1< diff --git a/test/main.test.ts b/test/main.test.ts index 5bad848..c151761 100644 --- a/test/main.test.ts +++ b/test/main.test.ts @@ -1,5 +1,6 @@ // SPDX-License-Identifier: Apache-2.0 +import * as v from "valibot"; import { expect, expectTypeOf, test } from "vitest"; import z from "zod"; import { @@ -186,6 +187,41 @@ test("async output schema", async () => { } }); +test("Valibot async schemas always return promises", async () => { + const asyncOutput = v.pipeAsync( + v.string(), + v.checkAsync(async (value) => value !== "bad"), + ); + const outputProcedure = zagora() + .input(v.string()) + .output(asyncOutput) + .handler((_, input) => input) + .callable(); + + const invalidInputResult = outputProcedure(123 as any); + expect(invalidInputResult).toBeInstanceOf(Promise); + expect((await invalidInputResult).ok).toBe(false); + + const asyncError = v.pipeAsync( + v.object({ message: v.string() }), + v.checkAsync(async () => true), + ); + const errorProcedure = zagora() + .input(v.string()) + .errors({ ASYNC_ERROR: asyncError }) + .handler(({ errors }, input) => { + if (input === "fail") { + throw errors.ASYNC_ERROR({ message: "failed" }); + } + return input; + }) + .callable(); + + const successResult = errorProcedure("success"); + expect(successResult).toBeInstanceOf(Promise); + expect((await successResult).ok).toBe(true); +}); + test("handleError with async schema validation", async () => { const asyncErrorSchema = z.object({ message: z diff --git a/test/types-testing.test.ts b/test/types-testing.test.ts index 2391226..80a94c5 100644 --- a/test/types-testing.test.ts +++ b/test/types-testing.test.ts @@ -28,6 +28,7 @@ */ import type { StandardSchemaV1 } from "@standard-schema/spec"; +import * as v from "valibot"; import { expect, expectTypeOf, test } from "vitest"; import { z } from "zod"; import type { @@ -41,8 +42,10 @@ import { Zagora, zagora } from "../src/index"; import type { AnySchema, ConditionalAsync, + HasAsyncSchema, InferSchemaOutputSafe, IsAny, + IsAsyncSchema, IsOptional, IsPromise, ResolvedProcedure, @@ -158,6 +161,69 @@ test("ConditionalAsync - conditionally wraps result in Promise", () = >(); }); +test("Valibot async schemas produce async procedure types", () => { + const syncSchema = v.string(); + const asyncSchema = v.pipeAsync( + v.string(), + v.checkAsync(async (value) => value.length > 0), + ); + + expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema + >().toEqualTypeOf(); + + const syncProcedure = zagora() + .input(syncSchema) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const asyncInputProcedure = zagora() + .input(asyncSchema) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const asyncOutputProcedure = zagora() + .input(syncSchema) + .output(asyncSchema) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const asyncErrorProcedure = zagora() + .input(syncSchema) + .errors({ ASYNC_ERROR: asyncSchema }) + .handler(({ errors }, input) => { + if (!input) { + throw errors.ASYNC_ERROR(input); + } + return input; + }) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const autoCallableProcedure = zagora({ + autoCallable: true, + disableOptions: true, + }) + .input(asyncSchema) + .handler((input) => input); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); +}); + // ============================================================================= // UppercaseKeys Type Tests // ============================================================================= From 06be2ab0401f47da8e7ecc999ccb4b0517bcc76a Mon Sep 17 00:00:00 2001 From: Olsten Larck Date: Thu, 30 Jul 2026 23:48:38 +0000 Subject: [PATCH 2/4] cover async validation failures --- test/main.test.ts | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/test/main.test.ts b/test/main.test.ts index c151761..abb0854 100644 --- a/test/main.test.ts +++ b/test/main.test.ts @@ -202,6 +202,10 @@ test("Valibot async schemas always return promises", async () => { expect(invalidInputResult).toBeInstanceOf(Promise); expect((await invalidInputResult).ok).toBe(false); + const invalidOutputResult = outputProcedure("bad"); + expect(invalidOutputResult).toBeInstanceOf(Promise); + expect((await invalidOutputResult).ok).toBe(false); + const asyncError = v.pipeAsync( v.object({ message: v.string() }), v.checkAsync(async () => true), @@ -220,6 +224,10 @@ test("Valibot async schemas always return promises", async () => { const successResult = errorProcedure("success"); expect(successResult).toBeInstanceOf(Promise); expect((await successResult).ok).toBe(true); + + const failedErrorResult = errorProcedure("fail"); + expect(failedErrorResult).toBeInstanceOf(Promise); + expect((await failedErrorResult).ok).toBe(false); }); test("handleError with async schema validation", async () => { From 728b05aa08e9302cca74274dd9d4e2ed7dcb642e Mon Sep 17 00:00:00 2001 From: Olsten Larck Date: Fri, 31 Jul 2026 00:13:43 +0000 Subject: [PATCH 3/4] preserve mixed schema return types --- src/index.ts | 31 +++++++++++++------------- src/types.ts | 45 ++++++++++++++++++++++++++++++++------ test/main.test.ts | 21 ++++++++++++++++++ test/types-testing.test.ts | 43 ++++++++++++++++++++++++++++++++++++ 4 files changed, 118 insertions(+), 22 deletions(-) diff --git a/src/index.ts b/src/index.ts index 122e82a..4e26a26 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,7 @@ import type { ConditionalAsync, IsPromise } from "./is-promise"; import type { AnySchema, CacheAdapter, + ConditionalSchemaAsync, HasAsyncSchema, InferOutput, InferSchemaInput, @@ -260,14 +261,16 @@ export class Zagora< ): TAutoCallable extends true ? ResolvedProcedure< TInputSchema, - HasAsyncSchema extends true - ? Promise< - ZagoraResult, TErrorsMap, any> - > - : ConditionalAsync< - ReturnType, - ZagoraResult, TErrorsMap, any> - > + ConditionalSchemaAsync< + HasAsyncSchema, + ConditionalAsync< + ReturnType, + ZagoraResult, TErrorsMap, any> + >, + Promise< + ZagoraResult, TErrorsMap, any> + > + > > : Zagora< TFn, @@ -450,13 +453,11 @@ export class Zagora< TResolvedResult >; - type TResult = HasAsyncSchema< - TInputSchema, - TOutputSchema, - TErrorsMap - > extends true - ? Promise - : ConditionalAsync, Result>; + type TResult = ConditionalSchemaAsync< + HasAsyncSchema, + ConditionalAsync, Result>, + Promise + >; type TFinalResult = TCache extends { has(key: string): infer A; diff --git a/src/types.ts b/src/types.ts index 7abf753..4430677 100644 --- a/src/types.ts +++ b/src/types.ts @@ -13,20 +13,51 @@ export type Schema = StandardSchemaV1; export type AnySchema = Schema; // TEST: with expect-type -export type IsAsyncSchema = T extends { readonly async: true } - ? true +export type IsAsyncSchema = [T] extends [never] + ? false + : T extends { readonly async: infer TAsync } + ? [TAsync] extends [true] + ? true + : true extends TAsync + ? boolean + : false + : false; + +type SchemaMapAsyncState = T extends Record + ? true extends { + [K in keyof T]: [IsAsyncSchema] extends [true] ? true : false; + }[keyof T] + ? true + : true extends { + [K in keyof T]: true extends IsAsyncSchema ? true : false; + }[keyof T] + ? boolean + : false : false; -type ErrorSchemas = T extends Record ? T[keyof T] : never; +type IsDefinitelyAsync = [T] extends [true] ? true : false; +type IsPossiblyAsync = true extends T ? true : false; // TEST: with expect-type export type HasAsyncSchema = true extends - | IsAsyncSchema - | IsAsyncSchema - | IsAsyncSchema> + | IsDefinitelyAsync> + | IsDefinitelyAsync> + | IsDefinitelyAsync> ? true - : false; + : true extends + | IsPossiblyAsync> + | IsPossiblyAsync> + | IsPossiblyAsync> + ? boolean + : false; + +// TEST: with expect-type +export type ConditionalSchemaAsync< + TAsync extends boolean, + TSync, + TAsyncResult, +> = TAsync extends true ? TAsyncResult : TSync; export type SchemaIssue = StandardSchemaV1.Issue; diff --git a/test/main.test.ts b/test/main.test.ts index abb0854..8cda383 100644 --- a/test/main.test.ts +++ b/test/main.test.ts @@ -230,6 +230,27 @@ test("Valibot async schemas always return promises", async () => { expect((await failedErrorResult).ok).toBe(false); }); +test("union-typed Valibot schemas preserve runtime return shape", async () => { + const syncSchema = v.string(); + const asyncSchema = v.pipeAsync( + v.string(), + v.checkAsync(async () => true), + ); + const createProcedure = (schema: typeof syncSchema | typeof asyncSchema) => + zagora() + .input(schema) + .handler((_, input) => input) + .callable(); + + const syncResult = createProcedure(syncSchema)("sync"); + expect(syncResult).not.toBeInstanceOf(Promise); + expect((await syncResult).ok).toBe(true); + + const asyncResult = createProcedure(asyncSchema)("async"); + expect(asyncResult).toBeInstanceOf(Promise); + expect((await asyncResult).ok).toBe(true); +}); + test("handleError with async schema validation", async () => { const asyncErrorSchema = z.object({ message: z diff --git a/test/types-testing.test.ts b/test/types-testing.test.ts index 80a94c5..fefcdea 100644 --- a/test/types-testing.test.ts +++ b/test/types-testing.test.ts @@ -42,6 +42,7 @@ import { Zagora, zagora } from "../src/index"; import type { AnySchema, ConditionalAsync, + ConditionalSchemaAsync, HasAsyncSchema, InferSchemaOutputSafe, IsAny, @@ -168,11 +169,34 @@ test("Valibot async schemas produce async procedure types", () => { v.checkAsync(async (value) => value.length > 0), ); + type MixedSchema = typeof syncSchema | typeof asyncSchema; + expectTypeOf>().toEqualTypeOf(); expectTypeOf>().toEqualTypeOf(); + expectTypeOf>().toEqualTypeOf(); expectTypeOf< HasAsyncSchema >().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema + >().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema< + undefined, + undefined, + { SYNC: typeof syncSchema; ASYNC: typeof asyncSchema } + > + >().toEqualTypeOf(); + expectTypeOf< + HasAsyncSchema< + undefined, + undefined, + { VALUE: typeof syncSchema } | { VALUE: typeof asyncSchema } + > + >().toEqualTypeOf(); + expectTypeOf< + ConditionalSchemaAsync + >().toEqualTypeOf<"sync" | "async">(); const syncProcedure = zagora() .input(syncSchema) @@ -190,6 +214,16 @@ test("Valibot async schemas produce async procedure types", () => { IsPromise> >().toEqualTypeOf(); + const createMixedProcedure = (schema: MixedSchema) => + zagora() + .input(schema) + .handler((_, input) => input) + .callable(); + const mixedProcedure = createMixedProcedure(syncSchema); + expectTypeOf>().toEqualTypeOf< + ReturnType | ReturnType + >(); + const asyncOutputProcedure = zagora() .input(syncSchema) .output(asyncSchema) @@ -222,6 +256,15 @@ test("Valibot async schemas produce async procedure types", () => { expectTypeOf< IsPromise> >().toEqualTypeOf(); + + const createMixedAutoCallable = (schema: MixedSchema) => + zagora({ autoCallable: true, disableOptions: true }) + .input(schema) + .handler((input) => input); + const mixedAutoCallableProcedure = createMixedAutoCallable(syncSchema); + expectTypeOf>().toEqualTypeOf< + ReturnType + >(); }); // ============================================================================= From 6471494cc6d41967cc81e797b27a2710ad1ae72e Mon Sep 17 00:00:00 2001 From: Olsten Larck Date: Fri, 31 Jul 2026 00:36:41 +0000 Subject: [PATCH 4/4] cover async error maps --- test/types-testing.test.ts | 22 +++++++++++++++++++++- 1 file changed, 21 insertions(+), 1 deletion(-) diff --git a/test/types-testing.test.ts b/test/types-testing.test.ts index fefcdea..af3b85b 100644 --- a/test/types-testing.test.ts +++ b/test/types-testing.test.ts @@ -235,8 +235,11 @@ test("Valibot async schemas produce async procedure types", () => { const asyncErrorProcedure = zagora() .input(syncSchema) - .errors({ ASYNC_ERROR: asyncSchema }) + .errors({ SYNC_ERROR: syncSchema, ASYNC_ERROR: asyncSchema }) .handler(({ errors }, input) => { + if (input === "sync") { + throw errors.SYNC_ERROR(input); + } if (!input) { throw errors.ASYNC_ERROR(input); } @@ -247,6 +250,23 @@ test("Valibot async schemas produce async procedure types", () => { IsPromise> >().toEqualTypeOf(); + type MixedErrorsMap = + | { SYNC_ERROR: typeof syncSchema } + | { ASYNC_ERROR: typeof asyncSchema }; + const createMixedErrorsMapProcedure = (errorsMap: MixedErrorsMap) => + zagora() + .input(syncSchema) + .errors(errorsMap) + .handler((_, input) => input) + .callable(); + const mixedErrorsMapProcedure = createMixedErrorsMapProcedure({ + SYNC_ERROR: syncSchema, + }); + type MixedErrorsMapResult = ReturnType; + expectTypeOf().toEqualTypeOf< + Awaited | Promise> + >(); + const autoCallableProcedure = zagora({ autoCallable: true, disableOptions: true,