fortify-schema
Version:
A modern TypeScript validation library designed around familiar interface syntax and powerful conditional validation. Experience schema validation that feels natural to TypeScript developers while unlocking advanced runtime validation capabilities.
1,517 lines (1,505 loc) • 80.6 kB
TypeScript
/**
* Core types and interfaces for the FortifyJS Schema system
*/
/**
* Rich validation error with detailed information
*/
interface ValidationError {
/** Field path where the error occurred (e.g., ['user', 'profile', 'email']) */
path: string[];
/** Human-readable error message */
message: string;
/** Error code for programmatic handling */
code: string;
/** Expected value or type */
expected: string;
/** Actual received value */
received: any;
/** Type of the received value */
receivedType: string;
/** Additional context or suggestions */
context?: {
suggestion?: string;
allowedValues?: any[];
constraints?: Record<string, any>;
};
}
/**
* Schema validation result with rich error information
*/
interface SchemaValidationResult<T = any> {
success: boolean;
data?: T;
errors: ValidationError[];
warnings: string[];
}
/**
* Base schema configuration options
*/
interface BaseSchemaOptions {
optional?: boolean;
nullable?: boolean;
default?: any;
}
/**
* String schema validation options
*/
interface StringSchemaOptions extends BaseSchemaOptions {
minLength?: number;
maxLength?: number;
pattern?: RegExp;
format?: "email" | "url" | "uuid" | "phone" | "slug" | "username";
}
/**
* Number schema validation options
*/
interface NumberSchemaOptions extends BaseSchemaOptions {
min?: number;
max?: number;
integer?: boolean;
positive?: boolean;
precision?: number;
}
/**
* Boolean schema validation options
*/
interface BooleanSchemaOptions extends BaseSchemaOptions {
strict?: boolean;
}
/**
* Array schema validation options
*/
interface ArraySchemaOptions extends BaseSchemaOptions {
minLength?: number;
maxLength?: number;
unique?: boolean;
}
/**
* Object schema validation options
*/
interface ObjectSchemaOptions extends BaseSchemaOptions {
strict?: boolean;
allowUnknown?: boolean;
}
/**
* Schema type definitions
*/
type SchemaType = "string" | "number" | "boolean" | "array" | "object" | "date" | "any";
/**
* Schema definition for object properties
*/
type SchemaDefinition = {
[key: string]: SchemaConfig;
};
/**
* Complete schema configuration
*/
interface SchemaConfig {
type: SchemaType;
options?: BaseSchemaOptions;
elementSchema?: SchemaConfig;
properties?: SchemaDefinition;
validator?: (value: any) => void;
}
/**
* Constant value wrapper to distinguish from string types
*/
interface ConstantValue {
const: string | number | boolean;
}
/**
* Union value wrapper for proper type inference
*/
interface UnionValue<T extends readonly string[] = readonly string[]> {
union: T;
}
/**
* Optional constant value wrapper
*/
interface OptionalConstantValue {
const: string | number | boolean;
optional: true;
}
/**
* Optional schema interface wrapper
*/
interface OptionalSchemaInterface {
optional: true;
schema: SchemaInterface;
}
/**
* Schema definition using TypeScript-like interface syntax
*/
interface SchemaInterface {
[key: string]: SchemaFieldType | ConstantValue | OptionalConstantValue | SchemaInterface | SchemaInterface[] | any;
}
/**
* Field type definitions using string literals and objects
*/
type SchemaFieldType = "string" | "string?" | "number" | "number?" | "boolean" | "boolean?" | "date" | "date?" | "any" | "any?" | "email" | "email?" | "url" | "url?" | "uuid" | "uuid?" | "phone" | "phone?" | "slug" | "slug?" | "username" | "username?" | "ip" | "ip?" | "json" | "json?" | "json.fast" | "json.fast?" | "json.secure" | "json.secure?" | "password" | "password?" | "text" | "text?" | "hexcolor" | "hexcolor?" | "base64" | "base64?" | "jwt" | "jwt?" | "semver" | "semver?" | "object" | "object?" | "int" | "int?" | "positive" | "positive?" | "float" | "float?" | "string[]" | "string[]?" | "number[]" | "number[]?" | "boolean[]" | "boolean[]?" | "int[]" | "int[]?" | "email[]" | "email[]?" | "url[]" | "url[]?" | "ip[]" | "ip[]?" | "json[]" | "json[]?" | "json.fast[]" | "json.fast[]?" | "password[]" | "password[]?" | "text[]" | "text[]?" | "object[]" | "object[]?" | "hexcolor[]" | "hexcolor[]?" | "base64[]" | "base64[]?" | "jwt[]" | "jwt[]?" | "semver[]" | "semver[]?" | string | ConstantValue | OptionalConstantValue | UnionValue | SchemaInterface | SchemaInterface[] | OptionalSchemaInterface;
/**
* Schema validation options for fine-tuning
*/
interface SchemaOptions {
minLength?: number;
maxLength?: number;
pattern?: RegExp;
min?: number;
max?: number;
precision?: number;
minItems?: number;
maxItems?: number;
unique?: boolean;
strict?: boolean;
allowUnknown?: boolean;
required?: boolean;
default?: any;
loose?: boolean;
enablePerformanceMonitoring?: boolean;
enableOptimizations?: boolean;
cacheValidation?: boolean;
skipOptimization?: boolean;
}
type AllowUnknownSchema<T> = T & Record<string, any>;
/**
* TypeScript Interface-like Schema Definition System
*
* Allows defining schemas using TypeScript-like syntax with string literals
* that feel natural and are much easier to read and write.
*/
/**
* Interface Schema class for TypeScript-like schema definitions
*/
declare class InterfaceSchema<T = any> {
private definition;
private options;
private compiledFields;
private schemaKeys;
private ConditionalParser;
private compiledValidator?;
private schemaComplexity;
private isOptimized;
private precompiledValidator?;
private optimizationLevel;
constructor(definition: SchemaInterface, options?: SchemaOptions);
/**
* Check if a field type uses conditional syntax using secure regex pattern
*/
private isConditionalSyntax;
/**
* Apply performance optimizations based on schema characteristics
*/
private applyOptimizations;
/**
* Create precompiled validator for maximum speed
* SAFETY: Now includes recursion protection and cycle detection
*/
private createPrecompiledValidator;
/**
* Check if schema has nested conditional fields
* CRITICAL FIX: This prevents precompilation for schemas with nested conditionals
*/
private hasNestedConditionalFields;
/**
* Calculate schema complexity score
*/
private calculateComplexity;
/**
* Calculate maximum nesting depth to avoid optimization bugs
*/
private calculateMaxNestingDepth;
/**
* Pre-compile schema for faster validation
*/
private precompileSchema;
/**
* Validate data against the interface schema - ULTRA-OPTIMIZED version
*/
private validate;
/**
* Standard validation method (original implementation)
*/
private validateStandard;
/**
* Validate pre-compiled string field for maximum performance
*/
private validatePrecompiledStringField;
/**
* Validate individual field
*/
private validateField;
/**
* Validate string-based field types - optimized version
*/
private validateStringFieldType;
/**
* Validate basic types with constraints
*/
private validateBasicType;
/**
* Validate nested object with full data context for conditional field resolution
* CRITICAL FIX: This method ensures nested conditional validation has access to parent context
*/
private validateNestedObjectWithContext;
/**
* Validate enhanced conditional field using our new AST-based system
* FIXED: Now properly handles nested context for field resolution
*/
private validateEnhancedConditionalField;
/**
* Validate conditional field with full data context
*/
private validateConditionalFieldWithContext;
/**
* Evaluate a condition against a field value
*/
private evaluateCondition;
/**
* Validate conditional field based on other field values (legacy method)
*
* Note: This method is used when conditional validation is called without
* full data context. It provides a fallback validation approach.
*/
private validateConditionalField;
/**
* Helper method to validate a value against a schema type
*/
private validateSchemaType;
/**
* Parse and validate (throws on error)
*/
parse(data: T): T;
/**
* Safe parse (returns result object) - strictly typed input
*/
safeParse(data: T): SchemaValidationResult<T>;
/**
* Safe parse with unknown data (for testing invalid inputs)
* Use this when you need to test data that might not match the schema
*/
safeParseUnknown(data: unknown): SchemaValidationResult<T>;
/**
* Set schema options
*/
withOptions(opts: SchemaOptions): InterfaceSchema<T>;
/**
* Async validation - returns a promise with validation result
*/
parseAsync(data: T): Promise<T>;
/**
* Async safe parse - returns a promise with validation result object
*/
safeParseAsync(data: T): Promise<SchemaValidationResult<T>>;
/**
* Async safe parse with unknown data
*/
safeParseUnknownAsync(data: unknown): Promise<SchemaValidationResult<T>>;
/**
* Enable strict mode (no unknown properties allowed)
*/
strict(): InterfaceSchema<T>;
/**
* Enable loose mode (allow type coercion)
*/
loose(): InterfaceSchema<T>;
/**
* Allow unknown properties (not strict about extra fields)
* Returns a schema that accepts extra properties beyond the defined interface
*/
allowUnknown(): InterfaceSchema<AllowUnknownSchema<T>>;
/**
* Set minimum constraints
*/
min(value: number): InterfaceSchema<T>;
/**
* Set maximum constraints
*/
max(value: number): InterfaceSchema<T>;
/**
* Require unique array values
*/
unique(): InterfaceSchema<T>;
/**
* Set pattern for string validation
*/
pattern(regex: RegExp): InterfaceSchema<T>;
/**
* Set default value
*/
default(value: any): InterfaceSchema<T>;
}
/**
* Unified TypeScript Type Inference System
*
* Combines core schema type inference with advanced conditional analysis.
* This is the single source of truth for all TypeScript type operations.
*/
/**
* Core type mapping for basic field types
*/
type CoreTypeMap = {
string: string;
number: number;
boolean: boolean;
date: Date;
any: any;
email: string;
url: string;
uuid: string;
phone: string;
slug: string;
username: string;
int: number;
integer: number;
positive: number;
negative: number;
float: number;
double: number;
unknown: unknown;
void: undefined;
null: null;
undefined: undefined;
};
/**
* Extract base type from field type string (removes constraints and modifiers)
*/
type ExtractBaseType<T extends string> = T extends `${infer Base}(${string})` ? Base : T extends `${infer Base}?` ? Base : T extends `${infer Base}[]` ? Base : T extends `${infer Base}[]?` ? Base : T extends `${infer Base}!` ? Base : T extends `(${infer Content})?` ? Content : T extends `(${infer Content})` ? Content : T;
/**
* Check if field type is optional
*/
type IsOptional<T extends string> = T extends `${string}?` ? true : false;
/**
* Check if field type is an array
*/
type IsArray<T extends string> = T extends `${string}[]` | `${string}[]?` ? true : false;
/**
* Extract element type from array type, handling parentheses
*/
type ExtractElementType<T extends string> = T extends `${infer Element}[]` ? Element extends `(${infer UnionContent})` ? UnionContent : Element : T extends `${infer Element}[]?` ? Element extends `(${infer UnionContent})` ? UnionContent : Element : T;
/**
* Map field type string to TypeScript type
*/
type MapFieldType<T extends string> = IsArray<T> extends true ? Array<MapFieldType<ExtractElementType<T>>> : T extends `record<${infer K}, ${infer V}>` ? Record<MapFieldType<K> extends string | number | symbol ? MapFieldType<K> : string, MapFieldType<V>> : T extends `Record<${infer K}, ${infer V}>` ? Record<MapFieldType<K> extends string | number | symbol ? MapFieldType<K> : string, MapFieldType<V>> : T extends `when ${string} *? ${string}` ? InferConditionalType<T> : ExtractBaseType<T> extends `${string}|${string}` ? ParseUnionType<ExtractBaseType<T>> : T extends `=${infer Value}?` ? Value | undefined : T extends `=${infer Value}` ? Value : ExtractBaseType<T> extends keyof CoreTypeMap ? CoreTypeMap[ExtractBaseType<T>] : any;
/**
* Utility type to trim whitespace from string literal types
*/
type Trim<T extends string> = T extends ` ${infer Rest}` ? Trim<Rest> : T extends `${infer Rest} ` ? Trim<Rest> : T;
/**
* Parse union type string into union of literal types
*/
type ParseUnionType<T extends string> = T extends `(${infer Content})` ? ParseUnionType<Trim<Content>> : T extends `${infer First}|${infer Rest}` ? Trim<First> | ParseUnionType<Rest> : Trim<T>;
/**
* Handle optional fields
*/
type HandleOptional<T, IsOpt extends boolean> = IsOpt extends true ? T | undefined : T;
/**
* Infer type for a single field
*/
type InferFieldType$1<T> = T extends string ? HandleOptional<MapFieldType<T>, IsOptional<T>> : T extends ConstantValue ? T["const"] : T extends OptionalConstantValue ? T["const"] | undefined : T extends UnionValue<infer U> & {
optional: true;
} ? U[number] | undefined : T extends UnionValue<infer U> ? U[number] : T extends OptionalSchemaInterface ? InferSchemaType<T["schema"]> | undefined : T extends Array<infer U> ? Array<InferSchemaType<U>> : T extends object ? InferSchemaType<T> : any;
/**
* Main type inference for schema interfaces
* FIXED: Handle optional properties correctly in nested objects
*/
type InferSchemaType<T> = {
[K in keyof T as T[K] extends string ? IsOptional<T[K]> extends true ? never : K : K]: InferFieldType$1<T[K]>;
} & {
[K in keyof T as T[K] extends string ? IsOptional<T[K]> extends true ? K : never : never]?: InferFieldType$1<T[K]>;
};
type InferConditionalType<T extends string, ThenType = unknown, ElseType = unknown> = T extends `${string} *? ${infer Then} : ${infer Else}` ? Then extends `=${infer ThenValue}` ? Else extends `=${infer ElseValue}` ? ThenValue | ElseValue : ThenType | ElseType : ThenType | ElseType : ThenType | ElseType;
/**
* Enhanced schema modification utilities - transform, combine, and manipulate schemas
*/
declare class Mod {
/**
* Safely access schema internals with proper typing
*/
private static getSchemaInternals;
/**
* Merge multiple schemas into a single schema
* @example
* ```typescript
* const UserSchema = Interface({ id: "number", name: "string" });
* const ProfileSchema = Interface({ bio: "string?", avatar: "url?" });
*
* const MergedSchema = Mod.merge(UserSchema, ProfileSchema);
* // Result: { id: number, name: string, bio?: string, avatar?: string }
* ```
*/
static merge<T, U>(schema1: InterfaceSchema<T>, schema2: InterfaceSchema<U>): InterfaceSchema<T & U>;
/**
* Merge multiple schemas with conflict resolution
* @example
* ```typescript
* const schema1 = Interface({ id: "number", name: "string" });
* const schema2 = Interface({ id: "uuid", email: "email" });
*
* const merged = Mod.mergeDeep(schema1, schema2, "second"); // id becomes "uuid"
* ```
*/
static mergeDeep<T, U>(schema1: InterfaceSchema<T>, schema2: InterfaceSchema<U>, strategy?: "first" | "second" | "merge"): InterfaceSchema<T & U>;
/**
* Pick specific fields from a schema
*/
static pick<T, K extends keyof T>(schema: InterfaceSchema<T>, keys: K[]): InterfaceSchema<Pick<T, K>>;
/**
* Omit specific fields from a schema
*/
static omit<T, K extends keyof T>(schema: InterfaceSchema<T>, keys: K[]): InterfaceSchema<Omit<T, K>>;
/**
* Make all fields in a schema optional
*/
static partial<T>(schema: InterfaceSchema<T>): InterfaceSchema<Partial<T>>;
/**
* Make all fields in a schema required
*/
static required<T>(schema: InterfaceSchema<T>): InterfaceSchema<Required<T>>;
/**
* Make specific fields optional in a schema without modifying field types
*
* This method allows you to selectively make certain fields optional while keeping
* all other fields required. It's particularly useful when you want to create
* flexible versions of strict schemas for different use cases (e.g., partial updates,
* form validation, API endpoints with optional parameters).
*
* The method works with both primitive types and nested objects, properly handling
* the optional nature at the validation level while maintaining type safety.
*
* @param schema - The source schema to modify
* @param keys - Array of field names to make optional
* @returns A new schema with specified fields made optional
*
* @example Making primitive fields optional
* ```typescript
* const UserSchema = Interface({
* id: "number",
* name: "string",
* email: "email",
* phone: "string"
* });
*
* const FlexibleUserSchema = Mod.makeOptional(UserSchema, ["email", "phone"]);
*
* // Now accepts both:
* FlexibleUserSchema.parse({ id: 1, name: "John" }); // ✅ email and phone optional
* FlexibleUserSchema.parse({ id: 1, name: "John", email: "john@example.com" }); // ✅
* ```
*
* @example Making nested objects optional
* ```typescript
* const ProfileSchema = Interface({
* id: "number",
* name: "string",
* preferences: {
* theme: "light|dark",
* notifications: "boolean",
* language: "en|es|fr"
* },
* settings: {
* privacy: "public|private",
* newsletter: "boolean"
* }
* });
*
* const FlexibleProfileSchema = Mod.makeOptional(ProfileSchema, ["preferences", "settings"]);
*
* // Now accepts:
* FlexibleProfileSchema.parse({ id: 1, name: "John" }); // ✅ nested objects optional
* FlexibleProfileSchema.parse({
* id: 1,
* name: "John",
* preferences: { theme: "dark", notifications: true, language: "en" }
* }); // ✅
* ```
*
* @example Use case: API endpoints with optional parameters
* ```typescript
* const CreateUserSchema = Interface({
* name: "string",
* email: "email",
* password: "string",
* role: "admin|user|moderator",
* department: "string",
* startDate: "date"
* });
*
* // For user registration (minimal required fields)
* const RegisterSchema = Mod.makeOptional(CreateUserSchema, ["role", "department", "startDate"]);
*
* // For admin creation (all fields required)
* const AdminCreateSchema = CreateUserSchema;
*
* // For profile updates (most fields optional)
* const UpdateProfileSchema = Mod.makeOptional(CreateUserSchema, ["password", "role", "department", "startDate"]);
* ```
*/
static makeOptional<T, K extends keyof T>(schema: InterfaceSchema<T>, keys: K[]): InterfaceSchema<Omit<T, K> & Partial<Pick<T, K>>>;
/**
* Extend a schema with additional fields
*/
static extend<T, U extends SchemaInterface>(schema: InterfaceSchema<T>, extension: U): InterfaceSchema<T & InferSchemaType<U>>;
/**
* Create a deep partial version of a schema (makes ALL fields optional recursively)
*
* Unlike the regular `partial()` method which only makes top-level fields optional,
* `deepPartial()` recursively traverses the entire schema structure and makes every
* field at every nesting level optional. This is particularly useful for update
* operations, patch APIs, or form validation where users might only provide
* partial data at any level of nesting.
*
* @param schema - The source schema to make deeply partial
* @returns A new schema where all fields at all levels are optional
*
* @example Basic deep partial transformation
* ```typescript
* const UserSchema = Interface({
* id: "number",
* name: "string",
* profile: {
* bio: "string",
* avatar: "string",
* social: {
* twitter: "string",
* linkedin: "string"
* }
* }
* });
*
* const DeepPartialSchema = Mod.deepPartial(UserSchema);
*
* // All of these are now valid:
* DeepPartialSchema.parse({}); // ✅ Everything optional
* DeepPartialSchema.parse({ id: 1 }); // ✅ Only id provided
* DeepPartialSchema.parse({
* profile: {
* bio: "Developer"
* }
* }); // ✅ Partial nested data
* DeepPartialSchema.parse({
* profile: {
* social: {
* twitter: "@john"
* }
* }
* }); // ✅ Deep nested partial data
* ```
*
* @example Use case: API PATCH endpoints
* ```typescript
* const ArticleSchema = Interface({
* id: "number",
* title: "string",
* content: "string",
* metadata: {
* tags: "string[]",
* category: "string",
* seo: {
* title: "string",
* description: "string",
* keywords: "string[]"
* }
* },
* author: {
* id: "number",
* name: "string"
* }
* });
*
* // For PATCH /articles/:id - allow partial updates at any level
* const PatchArticleSchema = Mod.deepPartial(ArticleSchema);
*
* // Users can update just the SEO title:
* PatchArticleSchema.parse({
* metadata: {
* seo: {
* title: "New SEO Title"
* }
* }
* }); // ✅
* ```
*
* @example Difference from regular partial()
* ```typescript
* const NestedSchema = Interface({
* user: {
* name: "string",
* email: "email"
* }
* });
*
* const RegularPartial = Mod.partial(NestedSchema);
* // Type: { user?: { name: string, email: string } }
* // user is optional, but if provided, name and email are required
*
* const DeepPartial = Mod.deepPartial(NestedSchema);
* // Type: { user?: { name?: string, email?: string } }
* // user is optional, and if provided, name and email are also optional
* ```
*/
static deepPartial<T>(schema: InterfaceSchema<T>): InterfaceSchema<DeepPartial<T>>;
/**
* Transform field types using a mapper function
* @example
* ```typescript
* const UserSchema = Interface({ id: "number", name: "string" });
* const StringifiedSchema = Mod.transform(UserSchema, (type) =>
* type.replace("number", "string")
* );
* // Result: { id: string, name: string }
* ```
*/
static transform<T>(schema: InterfaceSchema<T>, mapper: (fieldType: string, fieldName: string) => string): InterfaceSchema<any>;
/**
* Rename fields in a schema
* @example
* ```typescript
* const UserSchema = Interface({ user_id: "number", user_name: "string" });
* const RenamedSchema = Mod.rename(UserSchema, {
* user_id: "id",
* user_name: "name"
* });
* // Result: { id: number, name: string }
* ```
*/
static rename<T>(schema: InterfaceSchema<T>, fieldMap: Record<string, string>): InterfaceSchema<any>;
/**
* Create a schema with default values that are automatically applied during validation
*
* This method allows you to specify default values that will be automatically applied
* to fields when they are missing or undefined in the input data. This is particularly
* useful for API endpoints, form processing, and configuration objects where you want
* to ensure certain fields always have sensible default values.
*
* Default values are applied during the validation process, so they don't modify the
* original schema definition but are included in the validated output.
*
* @param schema - The source schema to add defaults to
* @param defaultValues - Object mapping field names to their default values
* @returns A new schema that applies default values during validation
*
* @example Basic default values
* ```typescript
* const UserSchema = Interface({
* id: "number",
* name: "string",
* role: "string?",
* active: "boolean?",
* createdAt: "date?"
* });
*
* const UserWithDefaults = Mod.defaults(UserSchema, {
* role: "user",
* active: true,
* createdAt: new Date()
* });
*
* const result = UserWithDefaults.parse({
* id: 1,
* name: "John Doe"
* // role, active, and createdAt will be filled with defaults
* });
*
* console.log(result.data);
* // {
* // id: 1,
* // name: "John Doe",
* // role: "user",
* // active: true,
* // createdAt: 2023-12-01T10:30:00.000Z
* // }
* ```
*
* @example API configuration with defaults
* ```typescript
* const ApiConfigSchema = Interface({
* host: "string",
* port: "number?",
* timeout: "number?",
* retries: "number?",
* ssl: "boolean?",
* compression: "boolean?"
* });
*
* const ApiConfigWithDefaults = Mod.defaults(ApiConfigSchema, {
* port: 3000,
* timeout: 5000,
* retries: 3,
* ssl: false,
* compression: true
* });
*
* // Users only need to provide the host
* const config = ApiConfigWithDefaults.parse({
* host: "api.example.com"
* });
* // All other fields get sensible defaults
* ```
*
* @example Form processing with defaults
* ```typescript
* const ProfileFormSchema = Interface({
* name: "string",
* email: "email",
* theme: "string?",
* notifications: "boolean?",
* language: "string?"
* });
*
* const ProfileWithDefaults = Mod.defaults(ProfileFormSchema, {
* theme: "light",
* notifications: true,
* language: "en"
* });
*
* // Form submissions get defaults for unchecked/unselected fields
* const profile = ProfileWithDefaults.parse({
* name: "Jane Smith",
* email: "jane@example.com"
* // theme, notifications, language get defaults
* });
* ```
*
* @example Conditional defaults based on environment
* ```typescript
* const AppConfigSchema = Interface({
* environment: "development|staging|production",
* debug: "boolean?",
* logLevel: "string?",
* cacheEnabled: "boolean?"
* });
*
* const isDevelopment = process.env.NODE_ENV === "development";
*
* const AppConfigWithDefaults = Mod.defaults(AppConfigSchema, {
* debug: isDevelopment,
* logLevel: isDevelopment ? "debug" : "info",
* cacheEnabled: !isDevelopment
* });
* ```
*/
static defaults<T>(schema: InterfaceSchema<T>, defaultValues: Record<string, any>): InterfaceSchema<T>;
/**
* Create a strict version of a schema that rejects any additional properties
*
* By default, Fortify Schema ignores extra properties in the input data (they're
* simply not included in the validated output). The `strict()` method changes this
* behavior to actively reject any properties that aren't defined in the schema,
* making validation fail with an error.
*
* This is useful for APIs where you want to ensure clients aren't sending
* unexpected data, form validation where extra fields indicate errors, or
* configuration parsing where unknown options should be flagged.
*
* @param schema - The source schema to make strict
* @returns A new schema that rejects additional properties
*
* @example Basic strict validation
* ```typescript
* const UserSchema = Interface({
* id: "number",
* name: "string",
* email: "email"
* });
*
* const StrictUserSchema = Mod.strict(UserSchema);
*
* // This will succeed
* StrictUserSchema.parse({
* id: 1,
* name: "John",
* email: "john@example.com"
* }); // ✅
*
* // This will fail due to extra property
* StrictUserSchema.parse({
* id: 1,
* name: "John",
* email: "john@example.com",
* age: 30 // ❌ Error: Unexpected properties: age
* });
* ```
*
* @example API endpoint validation
* ```typescript
* const CreatePostSchema = Interface({
* title: "string",
* content: "string",
* tags: "string[]?",
* published: "boolean?"
* });
*
* const StrictCreatePostSchema = Mod.strict(CreatePostSchema);
*
* // Protect against typos or malicious extra data
* app.post('/posts', (req, res) => {
* const result = StrictCreatePostSchema.safeParse(req.body);
*
* if (!result.success) {
* return res.status(400).json({
* error: "Invalid request data",
* details: result.errors
* });
* }
*
* // Guaranteed to only contain expected fields
* const post = result.data;
* });
* ```
*
* @example Configuration validation
* ```typescript
* const DatabaseConfigSchema = Interface({
* host: "string",
* port: "number",
* username: "string",
* password: "string",
* database: "string"
* });
*
* const StrictDatabaseConfig = Mod.strict(DatabaseConfigSchema);
*
* // Catch configuration typos early
* const config = StrictDatabaseConfig.parse({
* host: "localhost",
* port: 5432,
* username: "admin",
* password: "secret",
* database: "myapp",
* connectionTimeout: 5000 // ❌ Error: Unknown config option
* });
* ```
*
* @example Comparison with default behavior
* ```typescript
* const Schema = Interface({ name: "string" });
* const StrictSchema = Mod.strict(Schema);
*
* const input = { name: "John", extra: "ignored" };
*
* // Default behavior: extra properties ignored
* const defaultResult = Schema.parse(input);
* console.log(defaultResult); // { name: "John" } - extra property ignored
*
* // Strict behavior: extra properties cause error
* const strictResult = StrictSchema.safeParse(input);
* console.log(strictResult.success); // false
* console.log(strictResult.errors); // [{ message: "Unexpected properties: extra" }]
* ```
*/
static strict<T>(schema: InterfaceSchema<T>): InterfaceSchema<T>;
/**
* Create a passthrough version of a schema that preserves additional properties
*
* By default, Fortify Schema ignores extra properties in the input data (they're
* not included in the validated output). The `passthrough()` method changes this
* behavior to explicitly include all additional properties in the validated result,
* effectively making the schema more permissive.
*
* This is useful for proxy APIs, data transformation pipelines, or situations
* where you want to validate known fields while preserving unknown ones for
* later processing or forwarding to other systems.
*
* @param schema - The source schema to make passthrough
* @returns A new schema that includes additional properties in the output
*
* @example Basic passthrough behavior
* ```typescript
* const UserSchema = Interface({
* id: "number",
* name: "string",
* email: "email"
* });
*
* const PassthroughUserSchema = Mod.passthrough(UserSchema);
*
* const result = PassthroughUserSchema.parse({
* id: 1,
* name: "John",
* email: "john@example.com",
* age: 30, // Extra property
* department: "IT" // Extra property
* });
*
* console.log(result);
* // {
* // id: 1,
* // name: "John",
* // email: "john@example.com",
* // age: 30, // ✅ Preserved
* // department: "IT" // ✅ Preserved
* // }
* ```
*
* @example API proxy with validation
* ```typescript
* const KnownUserFieldsSchema = Interface({
* id: "number",
* name: "string",
* email: "email",
* role: "admin|user|moderator"
* });
*
* const ProxyUserSchema = Mod.passthrough(KnownUserFieldsSchema);
*
* // Validate known fields while preserving unknown ones
* app.post('/users/proxy', (req, res) => {
* const result = ProxyUserSchema.safeParse(req.body);
*
* if (!result.success) {
* return res.status(400).json({
* error: "Invalid known fields",
* details: result.errors
* });
* }
*
* // Forward to another service with all data preserved
* const response = await externalAPI.createUser(result.data);
* res.json(response);
* });
* ```
*
* @example Data transformation pipeline
* ```typescript
* const CoreDataSchema = Interface({
* timestamp: "date",
* userId: "number",
* action: "string"
* });
*
* const FlexibleDataSchema = Mod.passthrough(CoreDataSchema);
*
* // Process events with varying additional metadata
* function processEvent(rawEvent: unknown) {
* const result = FlexibleDataSchema.safeParse(rawEvent);
*
* if (!result.success) {
* throw new Error("Invalid core event structure");
* }
*
* const event = result.data;
*
* // Core fields are validated and typed
* console.log(`User ${event.userId} performed ${event.action} at ${event.timestamp}`);
*
* // Additional metadata is preserved for downstream processing
* if ('metadata' in event) {
* processMetadata(event.metadata);
* }
*
* return event; // All data preserved
* }
* ```
*
* @example Comparison with default and strict behavior
* ```typescript
* const Schema = Interface({ name: "string" });
* const PassthroughSchema = Mod.passthrough(Schema);
* const StrictSchema = Mod.strict(Schema);
*
* const input = { name: "John", extra: "data", more: "fields" };
*
* // Default: extra properties ignored
* const defaultResult = Schema.parse(input);
* console.log(defaultResult); // { name: "John" }
*
* // Passthrough: extra properties included
* const passthroughResult = PassthroughSchema.parse(input);
* console.log(passthroughResult); // { name: "John", extra: "data", more: "fields" }
*
* // Strict: extra properties cause error
* const strictResult = StrictSchema.safeParse(input);
* console.log(strictResult.success); // false
* ```
*/
static passthrough<T>(schema: InterfaceSchema<T>): InterfaceSchema<T & Record<string, any>>;
/**
* Create a schema that accepts null values for all fields
* @example
* ```typescript
* const UserSchema = Interface({ id: "number", name: "string" });
* const NullableSchema = Mod.nullable(UserSchema);
* // Result: { id: number | null, name: string | null }
* ```
*/
static nullable<T>(schema: InterfaceSchema<T>): InterfaceSchema<{
[K in keyof T]: T[K] | null;
}>;
/**
* Get comprehensive metadata and statistics about a schema
*
* This method analyzes a schema and returns detailed information about its structure,
* including field counts, types, and other useful metadata. This is particularly
* useful for debugging, documentation generation, schema analysis tools, or
* building dynamic UIs based on schema structure.
*
* @param schema - The schema to analyze
* @returns Object containing detailed schema metadata
*
* @example Basic schema analysis
* ```typescript
* const UserSchema = Interface({
* id: "number",
* name: "string",
* email: "email?",
* profile: {
* bio: "string?",
* avatar: "string"
* },
* tags: "string[]?"
* });
*
* const info = Mod.info(UserSchema);
* console.log(info);
* // {
* // fieldCount: 5,
* // requiredFields: 3,
* // optionalFields: 2,
* // types: ["number", "string", "email?", "object", "string[]?"],
* // fields: ["id", "name", "email", "profile", "tags"]
* // }
* ```
*
* @example Using info for documentation generation
* ```typescript
* function generateSchemaDoc(schema: InterfaceSchema<any>, name: string) {
* const info = Mod.info(schema);
*
* return `
* ## ${name} Schema
*
* **Fields:** ${info.fieldCount} total (${info.requiredFields} required, ${info.optionalFields} optional)
*
* **Field Types:**
* ${info.fields.map((field, i) => `- ${field}: ${info.types[i]}`).join('\n')}
* `;
* }
*
* const doc = generateSchemaDoc(UserSchema, "User");
* console.log(doc);
* ```
*
* @example Schema complexity analysis
* ```typescript
* function analyzeSchemaComplexity(schema: InterfaceSchema<any>) {
* const info = Mod.info(schema);
*
* const complexity = {
* simple: info.fieldCount <= 5,
* hasOptionalFields: info.optionalFields > 0,
* hasArrays: info.types.some(type => type.includes('[]')),
* hasNestedObjects: info.types.includes('object'),
* typeVariety: new Set(info.types.map(type =>
* type.replace(/\?|\[\]/g, '')
* )).size
* };
*
* return complexity;
* }
*
* const complexity = analyzeSchemaComplexity(UserSchema);
* console.log(complexity);
* // {
* // simple: false,
* // hasOptionalFields: true,
* // hasArrays: true,
* // hasNestedObjects: true,
* // typeVariety: 4
* // }
* ```
*
* @example Dynamic form generation
* ```typescript
* function generateFormFields(schema: InterfaceSchema<any>) {
* const info = Mod.info(schema);
*
* return info.fields.map((fieldName, index) => {
* const fieldType = info.types[index];
* const isRequired = !fieldType.includes('?');
* const baseType = fieldType.replace(/\?|\[\]/g, '');
*
* return {
* name: fieldName,
* type: baseType,
* required: isRequired,
* isArray: fieldType.includes('[]'),
* inputType: getInputType(baseType) // Custom function
* };
* });
* }
*
* function getInputType(type: string): string {
* switch (type) {
* case 'string': return 'text';
* case 'number': return 'number';
* case 'email': return 'email';
* case 'date': return 'date';
* case 'boolean': return 'checkbox';
* default: return 'text';
* }
* }
*
* const formFields = generateFormFields(UserSchema);
* ```
*
* @example Schema validation and testing
* ```typescript
* function validateSchemaStructure(schema: InterfaceSchema<any>) {
* const info = Mod.info(schema);
* const issues: string[] = [];
*
* if (info.fieldCount === 0) {
* issues.push("Schema has no fields");
* }
*
* if (info.requiredFields === 0) {
* issues.push("Schema has no required fields");
* }
*
* if (info.fieldCount > 20) {
* issues.push("Schema might be too complex (>20 fields)");
* }
*
* const unknownTypes = info.types.filter(type =>
* !['string', 'number', 'boolean', 'date', 'email', 'object'].some(known =>
* type.replace(/\?|\[\]/g, '').includes(known)
* )
* );
*
* if (unknownTypes.length > 0) {
* issues.push(`Unknown types found: ${unknownTypes.join(', ')}`);
* }
*
* return {
* valid: issues.length === 0,
* issues,
* info
* };
* }
* ```
*/
static info<T>(schema: InterfaceSchema<T>): {
fieldCount: number;
requiredFields: number;
optionalFields: number;
types: string[];
fields: string[];
};
/**
* Clone a schema with optional modifications
* @example
* ```typescript
* const UserSchema = Interface({ id: "number", name: "string" });
* const ClonedSchema = Mod.clone(UserSchema, { preserveOptions: true });
* ```
*/
static clone<T>(schema: InterfaceSchema<T>, options?: {
preserveOptions?: boolean;
}): InterfaceSchema<T>;
}
type DeepPartial<T> = {
[P in keyof T]?: T[P] extends object ? DeepPartial<T[P]> : T[P];
};
/**
* Helper class for creating schema values
*/
declare class Make {
/**
* Create a constant value (safer than using raw values)
* @example
* ```typescript
* const schema = Interface({
* status: Make.const("pending"),
* version: Make.const(1.0),
* enabled: Make.const(true)
* });
* ```
*/
static const<const T extends string | number | boolean>(value: T): ConstantValue & {
const: T;
};
/**
* Create a union type (multiple allowed values) with proper type inference
* @example
* ```typescript
* const schema = Interface({
* status: Make.union("pending", "accepted", "rejected"),
* priority: Make.union("low", "medium", "high")
* });
* ```
*/
static union<const T extends readonly string[]>(...values: T): UnionValue<T>;
/**
* Create an optional union type with proper type inference
* @example
* ```typescript
* const schema = Interface({
* status: Make.unionOptional("pending", "accepted", "rejected")
* });
* ```
*/
static unionOptional<const T extends readonly string[]>(...values: T): UnionValue<T> & {
optional: true;
};
}
/**
* TypeScript Interface-like Schema System
*
* The most intuitive way to define schemas - just like TypeScript interfaces!
*
* @example
* ```typescript
* import { Interface as IF} from "fortify-schema";
*
* // Define schema like a TypeScript interface
* const UserSchema = IF({
* id: "number",
* email: "email",
* name: "string",
* age: "number?", // Optional
* isActive: "boolean?", // Optional
* tags: "string[]?", // Optional array
* role: "admin", // Constant value
* profile: { // Nested object
* bio: "string?",
* avatar: "url?"
* }
* });
*
* // Validate data
* const result = UserSchema.safeParse(userData);
* ```
*/
/**
* Create a schema using TypeScript interface-like syntax with full type inference
*
* @param definition - Schema definition using TypeScript-like syntax
* @param options - Optional validation options
* @returns InterfaceSchema instance with inferred types
*
* @example Basic Usage
* ```typescript
* const UserSchema = Interface({
* id: "number",
* email: "email",
* name: "string",
* age: "number?",
* isActive: "boolean?",
* tags: "string[]?"
* });
*
* // result is fully typed as:
* // SchemaValidationResult<{
* // id: number;
* // email: string;
* // name: string;
* // age?: number;
* // isActive?: boolean;
* // tags?: string[];
* // }>
* const result = UserSchema.safeParse(data);
* ```
*
* @example With Constraints
* ```typescript
* const UserSchema = Interface({
* username: "string(3,20)", // 3-20 characters
* age: "number(18,120)", // 18-120 years
* tags: "string[](1,10)?", // 1-10 tags, optional
* });
* ```
*
* @example Nested Objects
* ```typescript
* const OrderSchema = Interface({
* id: "number",
* customer: {
* name: "string",
* email: "email",
* address: {
* street: "string",
* city: "string",
* zipCode: "string"
* }
* },
* items: [{
* name: "string",
* price: "number",
* quantity: "int"
* }]
* });
* ```
*/
declare function Interface<const T extends SchemaInterface>(definition: T, options?: SchemaOptions): InterfaceSchema<InferSchemaType<T>>;
/**
* Type helper for inferring TypeScript types from schema definitions
*
* @example
* ```typescript
* const UserSchema = Interface({
* id: "number",
* email: "email",
* name: "string",
* age: "number?",
* tags: "string[]?"
* });
*
* // Infer the TypeScript type
* type User = InferType<typeof UserSchema>;
* // User = {
* // id: number;
* // email: string;
* // name: string;
* // age?: number;
* // tags?: string[];
* // }
* ```
*/
type InferType<T extends InterfaceSchema<any>> = T extends InterfaceSchema<infer U> ? U : never;
/**
* Available field types for schema definitions
*/
declare const FieldTypes: {
readonly STRING: "string";
readonly STRING_OPTIONAL: "string?";
readonly NUMBER: "number";
readonly NUMBER_OPTIONAL: "number?";
readonly BOOLEAN: "boolean";
readonly BOOLEAN_OPTIONAL: "boolean?";
readonly DATE: "date";
readonly DATE_OPTIONAL: "date?";
readonly ANY: "any";
readonly ANY_OPTIONAL: "any?";
readonly EMAIL: "email";
readonly EMAIL_OPTIONAL: "email?";
readonly URL: "url";
readonly URL_OPTIONAL: "url?";
readonly UUID: "uuid";
readonly UUID_OPTIONAL: "uuid?";
readonly PHONE: "phone";
readonly PHONE_OPTIONAL: "phone?";
readonly SLUG: "slug";
readonly SLUG_OPTIONAL: "slug?";
readonly USERNAME: "username";
readonly USERNAME_OPTIONAL: "username?";
readonly INT: "int";
readonly INT_OPTIONAL: "int?";
readonly POSITIVE: "positive";
readonly POSITIVE_OPTIONAL: "positive?";
readonly FLOAT: "float";
readonly FLOAT_OPTIONAL: "float?";
readonly STRING_ARRAY: "string[]";
readonly STRING_ARRAY_OPTIONAL: "string[]?";
readonly NUMBER_ARRAY: "number[]";
readonly NUMBER_ARRAY_OPTIONAL: "number[]?";
readonly BOOLEAN_ARRAY: "boolean[]";
readonly BOOLEAN_ARRAY_OPTIONAL: "boolean[]?";
readonly INT_ARRAY: "int[]";
readonly INT_ARRAY_OPTIONAL: "int[]?";
readonly EMAIL_ARRAY: "email[]";
readonly EMAIL_ARRAY_OPTIONAL: "email[]?";
readonly URL_ARRAY: "url[]";
readonly URL_ARRAY_OPTIONAL: "url[]?";
readonly RECORD_STRING_ANY: "record<string,any>";
readonly RECORD_STRING_ANY_OPTIONAL: "record<string,any>?";
readonly RECORD_STRING_STRING: "record<string,string>";
readonly RECORD_STRING_STRING_OPTIONAL: "record<string,string>?";
readonly RECORD_STRING_NUMBER: "record<string,number>";
readonly RECORD_STRING_NUMBER_OPTIONAL: "record<string,number>?";
};
/**
* Quick schema creation helpers
*/
declare const QuickSchemas: {
/**
* User schema with common fields
*/
User: InterfaceSchema<InferSchemaType<{
readonly id: "number";
readonly email: "email";
readonly name: "string";
readonly createdAt: "date?";
readonly updatedAt: "date?";
}>>;
/**
* API response schema
*/
APIResponse: InterfaceSchema<InferSchemaType<{
readonly success: "boolean";
readonly data: "any?";
readonly errors: "string[]?";
readonly timestamp: "date?";
}>>;
/**
* Pagination schema
*/
Pagination: InterfaceSchema<InferSchemaType<{
readonly page: "int";
readonly limit: "int";
readonly total: "int";
readonly hasNext: "boolean?";
readonly hasPrev: "boolean?";
}>>;
/**
* Address schema
*/
Address: InterfaceSchema<InferSchemaType<{
readonly street: "string";
readonly city: "string";
readonly state: "string?";
readonly zipCode: "string";
readonly country: "string";
}>>;
/**
* Contact info schema
*/
Contact: InterfaceSchema<InferSchemaType<{
readonly email: "email?";
readonly phone: "phone?";
readonly website: "url?";
}>>;
};
/**
* OpenAPI Converter - Convert schemas to OpenAPI specifications
*
* This module provides utilities to convert Fortify Schema definitions
* to OpenAPI 3.0 specifications for API documentation.
*/
/**
* OpenAPI converter for schema definitions
*/
declare class OpenAPIConverter {
/**
* Convert a schema to OpenAPI format
*/
static convertSchema(schema: SchemaInterface): OpenAPISchemaObject;
/**
* Convert a single field to OpenAPI property
*/
private static convertField;
/**
* Convert string-based field definitions
*/
private static convertStringField;
/**
* Convert object field definitions
*/
private static convertObjectField;
/**
* Parse string constraints from string(min,max) format
*/
private static parseStringConstraints;
/**
* Generate complete OpenAPI specification
*/
static generateOpenAPISpec(schema: SchemaInterface, options: OpenAPISpecOptions): OpenAPISpecification;
/**
* Generate schema reference for use in OpenAPI paths
*/
static generateSchemaReference(schemaName: string): OpenAPIReference;
/**
* Generate request body specification
*/
static generateRequestBody(schema: SchemaInterface, options?: RequestBodyOptions): OpenAPIRequestBody;
/**
* Generate res