Libraries
    Preparing search index...

    Class PromiseSchemaBuilder<TRequired, TNullable, TExplicitType, THasDefault, TExtensions, TResolvedTypeSchema, TResult>

    Schema builder for promise-like values. Validates that a value is a thenable (for example, an actual Promise or any object with a then function) and optionally carries a typed resolved-value schema so that the inferred TypeScript type is Promise<T> instead of Promise<any>.

    NOTE this class is exported only to give opportunity to extend it by inheriting. It is not recommended to create an instance of this class directly. Use promise() function instead.

    const schema = promise();
    const result = schema.validate(Promise.resolve(42));
    // result.valid === true
    const schema = promise().optional();
    const result = schema.validate(undefined);
    // result.valid === true
    // result.object === undefined
    import { promise, string, InferType } from '@cleverbrush/schema';

    const schema = promise(string());

    type PromiseResult = InferType<typeof schema>;
    // → Promise<string>

    // Introspect at runtime
    const info = schema.introspect();
    // info.resolvedType → StringSchemaBuilder

    Type Parameters

    Hierarchy (View Summary)

    Index

    Constructors

    Properties

    "[___hasDefault]": THasDefault

    Type-level brand encoding whether this schema has a default value. Not emitted at runtime — used by input type inference.

    "[___type]": TRequired extends true
        ? TNullable extends true ? TResult | null : TResult
        : (TNullable extends true ? TResult | null : TResult) | undefined

    Type-level brand encoding the inferred type of this schema. Not emitted at runtime — used only by InferType.

    Accessors

    • get "~standard"(): StandardSchemaV1.Props<
          ResolvedSchemaType<TResult, TRequired, TNullable>,
      >

      Standard Schema v1 interface.

      Exposes this schema as a Standard Schema v1 validator, enabling out-of-the-box interoperability with any library that consumes the spec — including tRPC, TanStack Form, React Hook Form, T3 Env, Hono, Elysia, next-safe-action, and 50+ other tools.

      Every SchemaBuilder subclass (all 13 builders) inherits this property automatically — no additional setup required.

      Shape of the returned object:

      • version — always 1 (Standard Schema spec version)
      • vendor'@cleverbrush/schema'
      • validate(value) — synchronous; wraps this builder's own .validate() and converts its result to the Standard Schema Result<Output> format:
        • Success: { value: <validated output> }
        • Failure: { issues: [{ message: string }, …] }

      The returned object is cached after the first access so repeated reads return the same reference (required by the spec).

      Returns StandardSchemaV1.Props<ResolvedSchemaType<TResult, TRequired, TNullable>>

      import { object, string, number } from '@cleverbrush/schema';

      const UserSchema = object({
      name: string().minLength(2),
      email: string().email(),
      age: number().min(18).optional(),
      });

      // Grab the Standard Schema interface
      const std = UserSchema['~standard'];
      // std.version === 1
      // std.vendor === '@cleverbrush/schema'

      const ok = std.validate({ name: 'Alice', email: 'alice@example.com' });
      // { value: { name: 'Alice', email: 'alice@example.com', age: undefined } }

      const fail = std.validate({ name: 'A', email: 'not-an-email' });
      // { issues: [{ message: 'minLength' }, { message: 'email' }] }

      // Pass directly to TanStack Form, T3 Env, tRPC, etc.:
      // validators: { onChange: UserSchema, onBlur: UserSchema }
    • get canSkipPreValidation(): boolean

      Whether preValidateSync can be skipped entirely. True when there are no preprocessors and no validators, so the only work would be the required check and wrapping in a noop transaction — which subclasses can do inline.

      Returns boolean

    • get hasDefault(): boolean

      Whether this schema has a default value configured via .default(). Exposed for fast-path validation in subclasses.

      Returns boolean

    • get isNullRequiredViolation(): boolean
      Protected

      Whether null should count as a required-constraint violation.

      By default null is treated the same as undefined for the purposes of the required check — i.e. a required schema rejects both. Subclasses that may legally receive null as a value (e.g. UnionSchemaBuilder when a NullSchemaBuilder option is present) can override this to false so that null bypasses the required check and is passed directly to their option-validation logic.

      Returns boolean

    Methods

    • Sets a fallback value for this schema. When validation fails for any reason, the fallback value is returned as a successful result instead of validation errors.

      This is useful for graceful degradation — for example, providing a safe default when parsing untrusted input that might not conform to the schema.

      Accepts either a static value or a factory function. Factory functions are called each time the fallback is needed (useful for mutable values like () => []).

      Unlike default, which only fires when the input is undefined, .catch() fires on any validation failure — type mismatch, constraint violation, etc.

      When .catch() is set, parse and parseAsync will never throw.

      Parameters

      • value: TResult | (() => TResult)

        the fallback value, or a factory function producing the fallback

      Returns this

      const schema = string().catch('unknown');
      schema.validate(42); // { valid: true, object: 'unknown' }
      schema.validate('hello'); // { valid: true, object: 'hello' }
      schema.parse(42); // 'unknown' (no throw)
      // Factory function for mutable fallbacks
      const schema = array(string()).catch(() => []);
      schema.validate(null); // { valid: true, object: [] }
      // Contrast with .default() — default fires only on undefined
      const d = string().default('anon');
      d.validate(undefined); // { valid: true, object: 'anon' } ← fires
      d.validate(42); // { valid: false, errors: [...] } ← does NOT fire

      const c = string().catch('anon');
      c.validate(undefined); // { valid: true, object: 'anon' } ← fires
      c.validate(42); // { valid: true, object: 'anon' } ← also fires
    • Protected method used to create a new instance of the Builder defined by the props object. Should be used to instantiate new builders to keep builder's immutability.

      Type Parameters

      • TReq extends boolean

      Parameters

      • props: PromiseSchemaBuilderCreateProps<TReq>

        arbitrary props object

      Returns this

    • Attaches a human-readable description to this schema as runtime metadata.

      The description has no effect on validation — it is purely informational. It is accessible via .introspect().description and is emitted as the description field by toJsonSchema() from @cleverbrush/schema-json.

      Useful for documentation generation, form labels, and AI tool descriptions.

      Parameters

      • text: string

      Returns this

      const schema = object({
      name: string().describe('The user\'s full name'),
      age: number().optional().describe('Age in years'),
      }).describe('A user object');

      schema.introspect().description; // 'A user object'
    • Attaches an example value to this schema instance.

      The example is purely metadata — it has no effect on validation. It is accessible via .introspect().example and is emitted as the example keyword in JSON Schema output and OpenAPI spec generation.

      Parameters

      Returns this

      import { string } from '@cleverbrush/schema';

      const Email = string().example('user@example.com');

      Email.introspect().example; // 'user@example.com'
    • Returns an object describing the current schema configuration.

      In addition to the base fields exposed by SchemaBuilder.introspect, the following field is included:

      Returns {
          catchValue: TResult | (() => TResult) | undefined;
          defaultValue: TResult | (() => TResult) | undefined;
          description: string | undefined;
          example: unknown;
          extensions: { [key: string]: unknown };
          hasCatch: boolean;
          hasDefault: boolean;
          isNullable: boolean;
          isReadonly: boolean;
          isRequired: boolean;
          preprocessors: readonly PreprocessorEntry<TResult>[];
          requiredValidationErrorMessageProvider: ValidationErrorMessageProvider<
              SchemaBuilder<any, any, any, any, any>,
          >;
          resolvedType: SchemaBuilder<any, any, any, any, any> | undefined;
          schemaName: string | undefined;
          type: string;
          validators: readonly ValidatorEntry<TResult>[];
      }

      • catchValue: TResult | (() => TResult) | undefined

        The catch/fallback value or factory function set via .catch().

      • defaultValue: TResult | (() => TResult) | undefined

        The default value or factory function.

      • description: string | undefined

        The human-readable description attached to this schema via .describe(), or undefined if none was set.

      • example: unknown

        An example value attached to this schema via .example(), or undefined if none was set.

      • extensions: { [key: string]: unknown }

        Extension metadata. Stores custom state set by schema extensions.

      • hasCatch: boolean

        Whether a catch/fallback value has been set on this schema via .catch().

      • hasDefault: boolean

        Whether a default value (or factory) has been set on this schema.

      • isNullable: boolean

        If set to true, schema values of null are considered valid.

      • isReadonly: boolean

        If set to true, the inferred type is marked as readonly. Type-level only — no runtime enforcement.

      • isRequired: boolean

        If set to false, schema will be optional (null or undefined values will be considered as valid).

      • preprocessors: readonly PreprocessorEntry<TResult>[]

        Array of preprocessor functions

      • requiredValidationErrorMessageProvider: ValidationErrorMessageProvider<SchemaBuilder<any, any, any, any, any>>

        Custom error message provider for the 'is required' validation error.

      • resolvedType: SchemaBuilder<any, any, any, any, any> | undefined

        Resolved-value schema set via hasResolvedType, or undefined if not set.

      • schemaName: string | undefined

        The logical name attached to this schema via .schemaName(), or undefined if none was set.

      • type: string

        String id of schema type, e.g. string', numberorobject`.

      • validators: readonly ValidatorEntry<TResult>[]

        Array of validator functions

      const schema = promise(string());

      const info = schema.introspect();
      // info.resolvedType instanceof StringSchemaBuilder
    • Synchronously validates the value and returns it if valid. Throws a SchemaValidationError if validation fails.

      Parameters

      • object: any

        the value to parse

      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

        optional validation context

      Returns TResult

      the validated value

      SchemaValidationError if validation fails

      Error if the schema contains async preprocessors, validators, or error message providers

    • Async version of pre-validation. Runs preprocessors, validators, and the required/optional check on object. Supports async preprocessors, validators, and error message providers.

      Parameters

      • object: any

        the value to pre-validate

      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

        optional validation context settings

      Returns Promise<PreValidationResult<any, { validatedObject: any }>>

      a PreValidationResult containing the preprocessed transaction, context, and any errors

    • Synchronous version of preValidateAsync. Throws at runtime if any preprocessor or validator returns a Promise.

      Parameters

      • object: any

        the value to pre-validate

      • Optionalcontext: ValidationContext<SchemaBuilder<any, any, any, any, {}>>

        optional validation context settings

      Returns PreValidationResult<any, { validatedObject: any }>

      a PreValidationResult containing the preprocessed transaction, context, and any errors

      Error if a preprocessor or validator returns a Promise (use preValidateAsync instead)

    • Attaches a logical name to this schema instance.

      The name is purely metadata — it has no effect on validation. It is accessible via .introspect().schemaName and can be consumed by any tool that introspects schemas at runtime, such as OpenAPI spec generators, documentation tools, form libraries, or code generators.

      Uniqueness is the responsibility of the consuming tool. Passing the same constant (same object reference) to multiple consumers is always safe; how conflicts between different instances with the same name are handled depends on the tool.

      Parameters

      • name: string

      Returns this

      import { object, string, number } from '@cleverbrush/schema';

      export const UserSchema = object({
      id: number(),
      name: string(),
      }).schemaName('User');

      UserSchema.introspect().schemaName; // 'User'
    • Internal

      Sets extension metadata by key. Returns a new schema instance with the extension data stored. The data survives fluent chaining. Used by extension authors inside defineExtension() callbacks.

      Parameters

      • key: string
      • value: unknown

      Returns this