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..4e26a26 100644 --- a/src/index.ts +++ b/src/index.ts @@ -8,6 +8,8 @@ import type { ConditionalAsync, IsPromise } from "./is-promise"; import type { AnySchema, CacheAdapter, + ConditionalSchemaAsync, + HasAsyncSchema, InferOutput, InferSchemaInput, InferSchemaInputSafe, @@ -203,7 +205,7 @@ export class Zagora< return new Zagora({ ...this["~zagora"], errorsMap, - }); + }) as any; } env( @@ -259,9 +261,15 @@ export class Zagora< ): TAutoCallable extends true ? ResolvedProcedure< TInputSchema, - ConditionalAsync< - ReturnType, - ZagoraResult, TErrorsMap, any> + ConditionalSchemaAsync< + HasAsyncSchema, + ConditionalAsync< + ReturnType, + ZagoraResult, TErrorsMap, any> + >, + Promise< + ZagoraResult, TErrorsMap, any> + > > > : Zagora< @@ -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 @@ -438,7 +453,11 @@ export class Zagora< TResolvedResult >; - type TResult = ConditionalAsync, Result>; + type TResult = ConditionalSchemaAsync< + HasAsyncSchema, + ConditionalAsync, Result>, + Promise + >; type TFinalResult = TCache extends { has(key: string): infer A; @@ -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 extends readonly [any, ...any[]] ? SpreadTuple, TFinalResult> : (arg: InferSchemaInput) => TFinalResult diff --git a/src/types.ts b/src/types.ts index 1d2ce33..4430677 100644 --- a/src/types.ts +++ b/src/types.ts @@ -12,6 +12,53 @@ export type Schema = StandardSchemaV1; export type AnySchema = Schema; +// TEST: with expect-type +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 IsDefinitelyAsync = [T] extends [true] ? true : false; +type IsPossiblyAsync = true extends T ? true : false; + +// TEST: with expect-type +export type HasAsyncSchema = + true extends + | IsDefinitelyAsync> + | IsDefinitelyAsync> + | IsDefinitelyAsync> + ? true + : 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; export type InferSchemaOutput = T extends StandardSchemaV1< diff --git a/test/main.test.ts b/test/main.test.ts index 5bad848..8cda383 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,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); +}); + 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..af3b85b 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,11 @@ import { Zagora, zagora } from "../src/index"; import type { AnySchema, ConditionalAsync, + ConditionalSchemaAsync, + HasAsyncSchema, InferSchemaOutputSafe, IsAny, + IsAsyncSchema, IsOptional, IsPromise, ResolvedProcedure, @@ -158,6 +162,131 @@ 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), + ); + + 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) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const asyncInputProcedure = zagora() + .input(asyncSchema) + .handler((_, input) => input) + .callable(); + expectTypeOf< + 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) + .handler((_, input) => input) + .callable(); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + 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> + >().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, + }) + .input(asyncSchema) + .handler((input) => input); + expectTypeOf< + IsPromise> + >().toEqualTypeOf(); + + const createMixedAutoCallable = (schema: MixedSchema) => + zagora({ autoCallable: true, disableOptions: true }) + .input(schema) + .handler((input) => input); + const mixedAutoCallableProcedure = createMixedAutoCallable(syncSchema); + expectTypeOf>().toEqualTypeOf< + ReturnType + >(); +}); + // ============================================================================= // UppercaseKeys Type Tests // =============================================================================