zod-config
Version:
Load configuration variables from multiple sources with flexible adapters, ensuring type safety with Zod.
79 lines (76 loc) • 1.85 kB
TypeScript
import * as z3 from 'zod/v3';
import * as z from 'zod/v4/core';
type SchemaConfig = z3.AnyZodObject | z.$ZodType<Record<string, unknown>>;
type ZodV4OutputHelper<T> = T extends z.$ZodType<any> ? z.infer<T> : never;
type InferredDataConfig<S extends SchemaConfig> = S extends z3.ZodType<infer T> ? T : ZodV4OutputHelper<S>;
type InferredErrorConfig<S extends SchemaConfig> = S extends z3.ZodType<infer T> ? z3.ZodError<T> : S extends z.$ZodType<infer U> ? z.$ZodError<U> : never;
/**
* Adapter type
*/
type Adapter<D extends SchemaConfig = SchemaConfig> = {
/**
* Name of the adapter
*/
name: string;
/**
* Read the config
*/
read: () => Promise<InferredDataConfig<D>>;
/**
* Whether to suppress errors
*/
silent?: boolean;
};
/**
* Config type
*/
type Config<S extends SchemaConfig = SchemaConfig> = {
/**
* Schema to validate the config against
*/
schema: S;
/**
* Adapters to use
*/
adapters?: Adapter[] | Adapter;
/**
* Function to call on success
*/
onSuccess?: (data: InferredDataConfig<S>) => void;
/**
* Function to call on error
*/
onError?: (error: InferredErrorConfig<S>) => void;
/**
* Logger to use
*/
logger?: Logger;
/**
* How to handle casing differences.
*/
keyMatching?: KeyMatching;
};
/**
* Logger type
*/
type Logger = {
/**
* Log a warning
*/
warn: (message: string) => void;
};
/**
* Base adapter props
*/
type BaseAdapterProps = {
/**
* Regular expression to filter keys
*/
regex?: RegExp;
/**
* Whether to suppress errors
*/
silent?: boolean;
};
type KeyMatching = "lenient" | "strict";
export { Adapter as A, BaseAdapterProps as B, Config as C, InferredDataConfig as I, Logger as L, SchemaConfig as S };