Skip to content
This repository was archived by the owner on Oct 5, 2026. It is now read-only.
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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<ZagoraResult>`. 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<ZagoraResult>` 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.

Expand Down
35 changes: 29 additions & 6 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@ import type { ConditionalAsync, IsPromise } from "./is-promise";
import type {
AnySchema,
CacheAdapter,
ConditionalSchemaAsync,
HasAsyncSchema,
InferOutput,
InferSchemaInput,
InferSchemaInputSafe,
Expand Down Expand Up @@ -203,7 +205,7 @@ export class Zagora<
return new Zagora({
...this["~zagora"],
errorsMap,
});
}) as any;
}

env<TNewEnvVarsMapSchema extends AnySchema, TEnvVars extends ZagoraEnvVars>(
Expand Down Expand Up @@ -259,9 +261,15 @@ export class Zagora<
): TAutoCallable extends true
? ResolvedProcedure<
TInputSchema,
ConditionalAsync<
ReturnType<TFn>,
ZagoraResult<InferOutput<TOutputSchema, TFn>, TErrorsMap, any>
ConditionalSchemaAsync<
HasAsyncSchema<TInputSchema, TOutputSchema, TErrorsMap>,
ConditionalAsync<
ReturnType<TFn>,
ZagoraResult<InferOutput<TOutputSchema, TFn>, TErrorsMap, any>
>,
Promise<
ZagoraResult<InferOutput<TOutputSchema, TFn>, TErrorsMap, any>
>
>
>
: Zagora<
Expand Down Expand Up @@ -318,6 +326,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
Expand Down Expand Up @@ -438,7 +453,11 @@ export class Zagora<
TResolvedResult
>;

type TResult = ConditionalAsync<ReturnType<THandlerFn>, Result>;
type TResult = ConditionalSchemaAsync<
HasAsyncSchema<TInputSchema, TOutputSchema, TErrorsMap>,
ConditionalAsync<ReturnType<THandlerFn>, Result>,
Promise<Result>
>;

type TFinalResult = TCache extends {
has(key: string): infer A;
Expand All @@ -454,7 +473,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<TInputSchema> extends readonly [any, ...any[]]
? SpreadTuple<InferSchemaInput<TInputSchema>, TFinalResult>
: (arg: InferSchemaInput<TInputSchema>) => TFinalResult
Expand Down
47 changes: 47 additions & 0 deletions src/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,53 @@ export type Schema<I, O = I> = StandardSchemaV1<I, O>;

export type AnySchema = Schema<any, any>;

// TEST: with expect-type
export type IsAsyncSchema<T> = [T] extends [never]
? false
: T extends { readonly async: infer TAsync }
? [TAsync] extends [true]
? true
: true extends TAsync
? boolean
: false
: false;

type SchemaMapAsyncState<T> = T extends Record<string, AnySchema>
? true extends {
[K in keyof T]: [IsAsyncSchema<T[K]>] extends [true] ? true : false;
}[keyof T]
? true
: true extends {
[K in keyof T]: true extends IsAsyncSchema<T[K]> ? true : false;
}[keyof T]
? boolean
: false
: false;

type IsDefinitelyAsync<T extends boolean> = [T] extends [true] ? true : false;
type IsPossiblyAsync<T extends boolean> = true extends T ? true : false;

// TEST: with expect-type
export type HasAsyncSchema<TInputSchema, TOutputSchema, TErrorsMap> =
true extends
| IsDefinitelyAsync<IsAsyncSchema<TInputSchema>>
| IsDefinitelyAsync<IsAsyncSchema<TOutputSchema>>
| IsDefinitelyAsync<SchemaMapAsyncState<TErrorsMap>>
? true
Comment thread
tunnckoCore marked this conversation as resolved.
Resolved
: true extends
| IsPossiblyAsync<IsAsyncSchema<TInputSchema>>
| IsPossiblyAsync<IsAsyncSchema<TOutputSchema>>
| IsPossiblyAsync<SchemaMapAsyncState<TErrorsMap>>
? boolean
: false;

// TEST: with expect-type
export type ConditionalSchemaAsync<
TAsync extends boolean,
TSync,
TAsyncResult,
> = TAsync extends true ? TAsyncResult : TSync;

export type SchemaIssue = StandardSchemaV1.Issue;

export type InferSchemaOutput<T extends AnySchema> = T extends StandardSchemaV1<
Expand Down
65 changes: 65 additions & 0 deletions test/main.test.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down Expand Up @@ -186,6 +187,70 @@ 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 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),
);
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);

const failedErrorResult = errorProcedure("fail");
expect(failedErrorResult).toBeInstanceOf(Promise);
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);
});
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved

test("handleError with async schema validation", async () => {
const asyncErrorSchema = z.object({
message: z
Expand Down
129 changes: 129 additions & 0 deletions test/types-testing.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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 {
Expand All @@ -41,8 +42,11 @@ import { Zagora, zagora } from "../src/index";
import type {
AnySchema,
ConditionalAsync,
ConditionalSchemaAsync,
HasAsyncSchema,
InferSchemaOutputSafe,
IsAny,
IsAsyncSchema,
IsOptional,
IsPromise,
ResolvedProcedure,
Expand Down Expand Up @@ -158,6 +162,131 @@ test("ConditionalAsync<T, Result> - 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),
);

type MixedSchema = typeof syncSchema | typeof asyncSchema;

expectTypeOf<IsAsyncSchema<typeof syncSchema>>().toEqualTypeOf<false>();
expectTypeOf<IsAsyncSchema<typeof asyncSchema>>().toEqualTypeOf<true>();
expectTypeOf<IsAsyncSchema<MixedSchema>>().toEqualTypeOf<boolean>();
expectTypeOf<
HasAsyncSchema<typeof asyncSchema, undefined, undefined>
>().toEqualTypeOf<true>();
expectTypeOf<
HasAsyncSchema<MixedSchema, undefined, undefined>
>().toEqualTypeOf<boolean>();
expectTypeOf<
HasAsyncSchema<
undefined,
undefined,
{ SYNC: typeof syncSchema; ASYNC: typeof asyncSchema }
>
>().toEqualTypeOf<true>();
expectTypeOf<
HasAsyncSchema<
undefined,
undefined,
{ VALUE: typeof syncSchema } | { VALUE: typeof asyncSchema }
>
>().toEqualTypeOf<boolean>();
expectTypeOf<
ConditionalSchemaAsync<boolean, "sync", "async">
>().toEqualTypeOf<"sync" | "async">();

const syncProcedure = zagora()
.input(syncSchema)
.handler((_, input) => input)
.callable();
expectTypeOf<
IsPromise<ReturnType<typeof syncProcedure>>
>().toEqualTypeOf<false>();

const asyncInputProcedure = zagora()
.input(asyncSchema)
.handler((_, input) => input)
.callable();
expectTypeOf<
IsPromise<ReturnType<typeof asyncInputProcedure>>
>().toEqualTypeOf<true>();

const createMixedProcedure = (schema: MixedSchema) =>
zagora()
.input(schema)
.handler((_, input) => input)
.callable();
const mixedProcedure = createMixedProcedure(syncSchema);
expectTypeOf<ReturnType<typeof mixedProcedure>>().toEqualTypeOf<
ReturnType<typeof syncProcedure> | ReturnType<typeof asyncInputProcedure>
>();

const asyncOutputProcedure = zagora()
.input(syncSchema)
.output(asyncSchema)
.handler((_, input) => input)
.callable();
expectTypeOf<
IsPromise<ReturnType<typeof asyncOutputProcedure>>
>().toEqualTypeOf<true>();

const asyncErrorProcedure = zagora()
.input(syncSchema)
.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);
}
return input;
})
.callable();
expectTypeOf<
IsPromise<ReturnType<typeof asyncErrorProcedure>>
>().toEqualTypeOf<true>();

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<typeof mixedErrorsMapProcedure>;
expectTypeOf<MixedErrorsMapResult>().toEqualTypeOf<
Awaited<MixedErrorsMapResult> | Promise<Awaited<MixedErrorsMapResult>>
>();

const autoCallableProcedure = zagora({
autoCallable: true,
disableOptions: true,
})
.input(asyncSchema)
.handler((input) => input);
expectTypeOf<
IsPromise<ReturnType<typeof autoCallableProcedure>>
>().toEqualTypeOf<true>();

const createMixedAutoCallable = (schema: MixedSchema) =>
zagora({ autoCallable: true, disableOptions: true })
.input(schema)
.handler((input) => input);
const mixedAutoCallableProcedure = createMixedAutoCallable(syncSchema);
expectTypeOf<ReturnType<typeof mixedAutoCallableProcedure>>().toEqualTypeOf<
ReturnType<typeof mixedProcedure>
>();
});

// =============================================================================
// UppercaseKeys Type Tests
// =============================================================================
Expand Down