import * as crypto from 'crypto';
import crypto__default from 'crypto';
import { EventEmitter } from 'events';
import { Request, Response } from 'express';

/**
 * Type definitions for the XyPrissSecurity library
 */

type RateLimitMiddlewareOptions$1 = any;
/**
 * Security level enum
 */
declare enum SecurityLevel$1 {
    STANDARD = "standard",
    HIGH = "high",
    MAXIMUM = "maximum"
}
/**
 * Token type enum
 */
declare enum TokenType {
    GENERAL = "general",
    API_KEY = "api_key",
    SESSION = "session",
    JWT = "jwt",
    TOTP = "totp"
}
/**
 * Hash algorithm enum - can be used as values
 */
declare enum HashAlgorithm$2 {
    SHA256 = "sha256",
    SHA512 = "sha512",
    SHA3_256 = "sha3-256",
    SHA3_512 = "sha3-512",
    BLAKE3 = "blake3",
    BLAKE2B = "blake2b",
    BLAKE2S = "blake2s",
    PBKDF2 = "pbkdf2"
}
/**
 * Supported hash algorithms - accepts both string literals AND enum values
 *
 * Usage examples:
 * - String literal: algorithm: "sha256"
 * - Enum value: algorithm: HashAlgorithmEnum.SHA256
 * - Both are type-safe and supported!
 */
type HashAlgorithmType = "sha256" | "sha512" | "sha3-256" | "sha3-512" | "blake3" | "blake2b" | "blake2s" | "pbkdf2";
/**
 * Key derivation algorithm enum
 */
declare enum KeyDerivationAlgorithm {
    PBKDF2 = "pbkdf2",
    ARGON2 = "argon2",
    BALLOON = "balloon"
}
/**
 * Entropy source enum
 */
declare enum EntropySource {
    SYSTEM = "system",
    BROWSER = "browser",
    USER = "user",
    NETWORK = "network",
    COMBINED = "combined",
    CSPRNG = "csprng",
    MATH_RANDOM = "math_random",
    CUSTOM = "custom"
}
/**
 * Secure token options
 */
interface SecureTokenOptions {
    /**
     * Length of the token
     * @default 32
     */
    length?: number;
    /**
     * Include uppercase letters
     * @default true
     */
    includeUppercase?: boolean;
    /**
     * Include lowercase letters
     * @default true
     */
    includeLowercase?: boolean;
    /**
     * Include numbers
     * @default true
     */
    includeNumbers?: boolean;
    /**
     * Include symbols
     * @default false
     */
    includeSymbols?: boolean;
    /**
     * Exclude similar characters (e.g., 1, l, I, 0, O)
     * @default false
     */
    excludeSimilarCharacters?: boolean;
    /**
     * Entropy level
     * @default 'high'
     */
    entropy: "high" | "maximum" | "standard";
    maxValidityLength?: number;
}
/**
 * Hash options
 */
interface HashOptions {
    /**
     * Salt for the hash
     * If not provided, a random salt will be generated
     */
    salt?: string | Uint8Array;
    /**
     * Pepper for the hash (secret server-side value)
     */
    pepper?: string | Uint8Array;
    /**
     * Number of iterations
     * @default 10000
     */
    iterations?: number;
    /**
     * Hash algorithm
     * @default 'sha256'
     */
    algorithm?: HashAlgorithm$2 | HashAlgorithmType;
    /**
     * Output format ()
     * @default 'hex'
     */
    outputFormat?: EncodingHashType$1;
    /**
     * Output length in bytes
     * @default 32
     */
    outputLength?: number;
}
/**
 * Key derivation options
 */
interface KeyDerivationOptions {
    /**
     * Salt for key derivation
     * If not provided, a random salt will be generated
     */
    salt?: string | Uint8Array;
    /**
     * Number of iterations
     * @default 100000
     */
    iterations?: number;
    /**
     * Key derivation algorithm
     * @default 'pbkdf2'
     */
    algorithm?: KeyDerivationAlgorithm | string;
    /**
     * Hash function to use (for PBKDF2)
     * @default 'sha256'
     */
    hashFunction?: HashAlgorithm$2 | string;
    /**
     * Output length in bytes
     * @default 32
     */
    keyLength?: number;
    /**
     * Memory cost for memory-hard functions (in KB)
     * @default 65536 (64 MB)
     */
    memoryCost?: number;
    /**
     * Parallelism factor for memory-hard functions
     * @default 4
     */
    parallelism?: number;
}
/**
 * API key options
 */
interface APIKeyOptions {
    /**
     * Prefix for the API key
     * @default ''
     */
    prefix?: string;
    /**
     * Include timestamp in the API key
     * @default true
     */
    includeTimestamp?: boolean;
    /**
     * Length of the random part
     * @default 32
     */
    randomPartLength?: number;
    /**
     * Separator between parts
     * @default '_'
     */
    separator?: string;
    /**
     * Encoding type for the API key
     */
    encoding?: EncodingHashType$1;
}
/**
 * Session token options
 */
interface SessionTokenOptions {
    /**
     * User ID to include in the token
     */
    userId?: string | number;
    /**
     * IP address to include in the token
     */
    ipAddress?: string;
    /**
     * User agent to include in the token
     */
    userAgent?: string;
    /**
     * Expiration time in seconds
     * @default 3600 (1 hour)
     */
    expiresIn?: number;
}
/**
 * Middleware options
 */
interface MiddlewareOptions {
    /**
     * Custom headers to add to the response
     * @default {}
     */
    customHeaders?: Record<string, string>;
    /**
     * Callback function to handle rate limit exceeded
     */
    onRateLimit?: (req: any, res: any) => void;
    /**
     * Callback function to handle CSRF errors
     */
    onCSRFError?: (req: any, res: any) => void;
    /**
     * Callback function to handle errors
     */
    onError?: (req: any, res: any) => void;
    /**
     * Callback function to handle metrics
     */
    metricsHook?: (metrics: any) => void;
    /**
     * Enable CSRF protection
     * @default false
     */
    csrfProtection?: boolean;
    /**
     * Enable secure headers
     * @default true
     */
    secureHeaders?: boolean;
    /**
     * Enable rate limiting
     * @default true
     */
    rateLimit?: boolean | RateLimitMiddlewareOptions$1;
    /**
     * Maximum requests per minute
     * @default 100
     */
    maxRequestsPerMinute?: number;
    /**
     * Secret for token generation
     * If not provided, a random secret will be generated (use Random.getRandomBytes)
     */
    tokenSecret?: string;
    /**
     * Name of the CSRF cookie
     * @default 'nehonix_xypriss_csrf'
     */
    cookieName?: string;
    /**
     * Name of the CSRF header
     * @default 'X-XyPriss_CSRF-Token'
     */
    headerName?: string;
    /**
     * Paths to exclude from CSRF protection
     * @default ['/api/health', '/api/status']
     */
    excludePaths?: string[];
    /**
     * Whether to log requests
     * @default true
     */
    logRequests?: boolean;
    /**
     * Logger to use
     * @default console
     */
    logger?: Console;
    /**
     * Content Security Policy header value
     * @default "default-src 'self'; script-src 'self'; object-src 'none'; frame-ancestors 'none'"
     */
    contentSecurityPolicy?: string;
}
/**
 * Crypto stats
 */
interface CryptoStats {
    /**
     * Number of tokens generated
     */
    tokensGenerated: number;
    /**
     * Number of hashes computed
     */
    hashesComputed: number;
    /**
     * Number of keys derived
     */
    keysDerivated: number;
    /**
     * Average entropy in bits
     */
    averageEntropyBits: number;
    /**
     * Timestamp of the last operation
     */
    lastOperationTime: string;
    /**
     * Performance metrics
     */
    performance: {
        /**
         * Average token generation time in milliseconds
         */
        tokenGenerationAvgMs: number;
        /**
         * Average hash computation time in milliseconds
         */
        hashComputationAvgMs: number;
        /**
         * Average key derivation time in milliseconds
         */
        keyDerivationAvgMs: number;
    };
    /**
     * Memory usage metrics
     */
    memory: {
        /**
         * Average memory usage in bytes
         */
        averageUsageBytes: number;
        /**
         * Peak memory usage in bytes
         */
        peakUsageBytes: number;
    };
}
/**
 * Security test result
 */
interface SecurityTestResult {
    /**
     * Whether all tests passed
     */
    passed: boolean;
    /**
     * Test results
     */
    results: {
        /**
         * Random number generation test
         */
        randomness: {
            passed: boolean;
            details: any;
        };
        /**
         * Hash function test
         */
        hashing: {
            passed: boolean;
            details: any;
        };
        /**
         * Timing attack resistance test
         */
        timingAttacks: {
            passed: boolean;
            details: any;
        };
    };
}
/**
 * Password strength result
 */
interface PasswordStrengthResult {
    /**
     * Password strength score (0-100)
     */
    score: number;
    /**
     * Feedback messages
     */
    feedback: string[];
    /**
     * Estimated time to crack
     */
    estimatedCrackTime: string;
    /**
     * Detailed analysis
     */
    analysis: {
        /**
         * Length score
         */
        length: number;
        /**
         * Entropy score
         */
        entropy: number;
        /**
         * Character variety score
         */
        variety: number;
        /**
         * Pattern penalty
         */
        patterns: number;
    };
}
interface EnhancedHashOptions extends HashOptions {
    strength?: HashStrength;
    memoryHard?: boolean;
    quantumResistant?: boolean;
    timingSafe?: boolean;
    validateInput?: boolean;
    secureWipe?: boolean;
}
type BaseEncodingType = "unicode" | "htmlEntity" | "punycode" | "asciihex" | "asciioct" | "rot13" | "base32" | "urlSafeBase64" | "jsEscape" | "cssEscape" | "utf7" | "quotedPrintable" | "decimalHtmlEntity";
type EncodingHashType$1 = "hex" | "base64" | "base64url" | "binary" | "utf8" | "buffer" | "base58" | BaseEncodingType;
interface SecureHashOptions {
    algorithm?: string;
    iterations?: number;
    salt?: string | Buffer | Uint8Array;
    pepper?: string | Buffer | Uint8Array;
    outputFormat?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer";
    keyDerivation?: "argon2" | "scrypt" | "pbkdf2" | "bcrypt";
    parallelism?: number;
    memorySize?: number;
    timeCost?: number;
    quantumResistant?: boolean;
    domainSeparation?: string;
}

/**
 * Hash types and interfaces
 * Centralized type definitions for the hash module
 */
declare enum HashStrength {
    WEAK = "WEAK",
    FAIR = "FAIR",
    GOOD = "GOOD",
    STRONG = "STRONG",
    MILITARY = "MILITARY"
}
type HashSecurityLevel = "LOW" | "MEDIUM" | "HIGH" | "MILITARY";
interface HashMonitoringResult {
    securityLevel: HashSecurityLevel;
    threats: string[];
    recommendations: string[];
    timestamp: number;
}
interface HashEntropyAnalysis {
    shannonEntropy: number;
    minEntropy: number;
    compressionRatio: number;
    randomnessScore: number;
    qualityGrade: "POOR" | "FAIR" | "GOOD" | "EXCELLENT";
    recommendations: string[];
}
interface HashAgilityResult {
    hash: string | Buffer;
    algorithm: string;
    fallbacks: string[];
    metadata: {
        version: string;
        timestamp: number;
        strength: string;
    };
}
interface HSMHashOptions {
    keySlot?: number;
    algorithm?: "sha256" | "sha512" | "sha3-256";
    outputFormat?: "hex" | "base64" | "buffer";
    validateIntegrity?: boolean;
}
interface SideChannelOptions {
    constantTime?: boolean;
    memoryProtection?: boolean;
    powerAnalysisResistant?: boolean;
    outputFormat?: "hex" | "base64" | "buffer";
}
interface HashConfiguration {
    algorithm: string;
    iterations: number;
    saltLength: number;
    keyLength: number;
    memoryCost?: number;
    timeCost?: number;
    parallelism?: number;
}
interface StrengthConfiguration {
    minIterations: number;
    saltLength: number;
    algorithm?: string;
    memoryCost?: number;
    timeCost?: number;
    parallelism?: number;
    hashLength?: number;
    fallbackIterations?: number;
}
interface HSMIntegrityResult {
    valid: boolean;
    details: string;
}
interface HashOperationData {
    input: string | Uint8Array;
    algorithm: string;
    iterations: number;
}
interface AgilityHashOptions {
    primaryAlgorithm?: "sha256" | "sha512" | "blake3" | "sha3-256";
    fallbackAlgorithms?: string[];
    futureProof?: boolean;
    outputFormat?: "hex" | "base64" | "buffer";
}

/**
 * Hash utilities - Common utility functions for hash operations
 */

declare class HashUtils {
    /**
     * Format hash output in the specified format
     * @param data - Data to format
     * @param format - Output format
     * @returns Formatted output
     */
    static formatOutput(data: Uint8Array | Buffer, format?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer"): string | Buffer;
    /**
     * Get strength-based configuration
     * @param strength - Hash strength level
     * @returns Configuration object
     */
    static getStrengthConfiguration(strength: HashStrength): StrengthConfiguration;
    /**
     * Get Argon2 configuration based on strength
     * @param strength - Hash strength level
     * @returns Argon2 configuration
     */
    static getArgon2Configuration(strength: HashStrength): StrengthConfiguration;
    /**
     * Get scrypt configuration based on strength
     * @param strength - Hash strength level
     * @returns Scrypt configuration
     */
    static getScryptConfiguration(strength: HashStrength): {
        N: number;
        r: number;
        p: number;
    };
    /**
     * Perform secure memory wipe
     * @param input - Input to wipe
     * @param salt - Salt to wipe
     * @param pepper - Pepper to wipe
     */
    static performSecureWipe(input: string | Buffer | Uint8Array, salt?: string | Buffer | Uint8Array, pepper?: string | Buffer | Uint8Array): void;
    /**
     * Validate hash algorithm
     * @param algorithm - Algorithm to validate
     * @returns True if valid
     */
    static isValidAlgorithm(algorithm: string): boolean;
    /**
     * Get algorithm security level
     * @param algorithm - Algorithm to check
     * @returns Security level
     */
    static getAlgorithmSecurityLevel(algorithm: string): "LOW" | "MEDIUM" | "HIGH" | "MILITARY";
    /**
     * Convert string or Uint8Array to Buffer
     * @param input - Input to convert
     * @returns Buffer
     */
    static toBuffer(input: string | Uint8Array | Buffer): Buffer;
    /**
     * Generate random salt with specified length
     * @param length - Salt length in bytes
     * @returns Random salt buffer
     */
    static generateRandomSalt(length: number): Buffer;
    /**
     * Combine multiple buffers securely
     * @param buffers - Buffers to combine
     * @returns Combined buffer
     */
    static combineBuffers(buffers: Buffer[]): Buffer;
    /**
     * XOR two buffers of equal length
     * @param a - First buffer
     * @param b - Second buffer
     * @returns XORed result
     */
    static xorBuffers(a: Buffer, b: Buffer): Buffer;
}

/**
 * Hash validator - Input validation and security checks
 */

declare class HashValidator {
    /**
     * Validate hash input for security
     * @param input - Input to validate
     * @param options - Validation options
     */
    static validateHashInput(input: string | Uint8Array, options: EnhancedHashOptions): void;
    /**
     * Check for weak patterns in input
     * @param input - String input to check
     * @returns True if weak patterns found
     */
    private static hasWeakPatterns;
    /**
     * Validate hash options
     * @param options - Options to validate
     */
    private static validateOptions;
    /**
     * Validate password strength
     * @param password - Password to validate
     * @returns Validation result
     */
    static validatePasswordStrength(password: string): {
        isSecure: boolean;
        score: number;
        issues: string[];
        recommendations: string[];
    };
    /**
     * Enhanced timing-safe string comparison
     * @param a - First string/buffer
     * @param b - Second string/buffer
     * @returns True if equal
     */
    static timingSafeEqual(a: string | Buffer | Uint8Array, b: string | Buffer | Uint8Array): boolean;
    /**
     * Manual timing-safe comparison implementation
     */
    private static manualTimingSafeEqual;
    /**
     * Validate salt quality
     * @param salt - Salt to validate
     * @returns Validation result
     */
    static validateSalt(salt: string | Buffer | Uint8Array): {
        isValid: boolean;
        issues: string[];
        recommendations: string[];
    };
}

/**
 * Hash Algorithms - Enterprise-grade cryptographic hashing
 * Maintains backward compatibility while adding quantum-resistant features
 */

declare class HashAlgorithms {
    private static readonly QUANTUM_ALGORITHMS;
    private static readonly SECURITY_CONSTANTS;
    /**
     * Initialize crypto libraries asynchronously (NEW METHOD)
     */
    static initialize(): Promise<void>;
    /**
     * Core secure hash function with multiple algorithm support
     *
     * BEHAVIOR: This method produces consistent hashes for the same input. Unlike Hash.createSecureHash(), this method
     * does NOT auto-generate random salts, ensuring deterministic results.
     *
     * Use this method when you need:
     * - Consistent hashes for data integrity verification
     * - Content-based hashing (like file checksums)
     * - Deterministic hash generation
     *
     * @param input - Input to hash
     * @param options - Hash options (salt is optional and won't be auto-generated)
     * @returns Hash result (consistent for same input/options)
     */
    static secureHash(input: string | Uint8Array, options?: {
        algorithm?: string;
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        pepper?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "base58" | "binary" | "base64url" | "buffer";
    }): string | Buffer;
    /**
     *  more algorithms and better implementations
     * Hash data with specified algorithm
     * @param data - Data to hash
     * @param algorithm - Algorithm to use
     * @returns Hash result
     */
    private static hashWithAlgorithm;
    /**
     *  real BLAKE3 implementation
     * BLAKE3 hash implementation
     * @param data - Data to hash
     * @returns BLAKE3 hash
     */
    private static blake3Hash;
    /**
     *  real BLAKE2b implementation
     * BLAKE2b hash implementation
     * @param data - Data to hash
     * @returns BLAKE2b hash
     */
    private static blake2bHash;
    /**
     *  real BLAKE2s implementation
     * BLAKE2s hash implementation
     * @param data - Data to hash
     * @returns BLAKE2s hash
     */
    private static blake2sHash;
    /**
     *  better security parameters
     * PBKDF2 hash implementation
     * @param data - Data to hash
     * @returns PBKDF2 hash
     */
    private static pbkdf2Hash;
    /**
     *  better constants and rounds
     * Fallback BLAKE3 implementation (simplified)
     * @param data - Data to hash
     * @returns Simplified BLAKE3-like hash
     */
    private static fallbackBlake3;
    /**
     *  quantum resistance option
     * Enhanced HMAC generation
     * @param algorithm - Hash algorithm
     * @param key - HMAC key
     * @param data - Data to authenticate
     * @param options - HMAC options
     * @returns HMAC digest
     */
    static createSecureHMAC(algorithm: "sha256" | "sha512" | "sha3-256" | "sha3-512", key: string | Buffer | Uint8Array, data: string | Buffer | Uint8Array, options?: {
        encoding?: "hex" | "base64" | "base64url";
        keyDerivation?: boolean;
        iterations?: number;
    }): string;
    /**
     *  better algorithm selection and quantum resistance
     * Multi-algorithm hash for quantum resistance
     * @param input - Input to hash
     * @param algorithms - Algorithms to use
     * @param iterations - Iterations per algorithm
     * @returns Combined hash result
     */
    static multiAlgorithmHash(input: string | Uint8Array, algorithms?: string[], iterations?: number): Buffer;
    /**
     *  better chunk processing and algorithms
     * Streamed hash for large data
     * @param algorithm - Hash algorithm
     * @param chunkSize - Chunk size for processing
     * @returns Hash stream processor
     */
    static createStreamHash(algorithm?: string, chunkSize?: number): {
        update: (chunk: Buffer) => void;
        digest: () => Buffer;
        reset: () => void;
    };
    /**
     *  better timing attack prevention
     * Constant-time hash comparison
     * @param hash1 - First hash
     * @param hash2 - Second hash
     * @returns True if hashes match
     */
    static constantTimeCompare(hash1: string | Buffer, hash2: string | Buffer): boolean;
    /**
     * NEW METHOD - Ultra-secure hash function with quantum resistance
     */
    static quantumResistantHash(input: string | Uint8Array, options?: SecureHashOptions): Promise<string | Buffer>;
    /**
     * NEW METHOD - Argon2 key derivation
     */
    private static argon2Derive;
    /**
     * NEW METHOD - Scrypt key derivation
     */
    private static scryptDerive;
    /**
     * NEW METHOD - BCrypt key derivation
     */
    private static bcryptDerive;
    /**
     * NEW METHOD - Enhanced PBKDF2 key derivation
     */
    private static pbkdf2Derive;
    /**
     * NEW METHOD - Multi-algorithm quantum-resistant hashing
     */
    private static multiQuantumHash;
    /**
     * NEW METHOD - Ultra-secure HMAC with quantum resistance
     */
    static createQuantumHMAC(algorithm: string, key: string | Buffer | Uint8Array, data: string | Buffer | Uint8Array, options?: {
        encoding?: "hex" | "base64" | "base64url";
        keyDerivation?: boolean;
        iterations?: number;
        quantumResistant?: boolean;
    }): Promise<string>;
    /**
     * NEW METHOD - BLAKE3-based HMAC
     */
    private static blake3HMAC;
    /**
     * NEW METHOD - Secure random salt generation
     */
    static generateSecureSalt(size?: number): Buffer;
    /**
     * NEW METHOD - Enhanced secure comparison with additional timing normalization
     */
    static secureCompare(hash1: string | Buffer, hash2: string | Buffer): boolean;
    /**
     * NEW METHOD - Secure hash verification
     */
    static verifyHash(input: string | Uint8Array, expectedHash: string | Buffer, options?: SecureHashOptions): Promise<boolean>;
    /**
     * NEW METHOD - Memory-hard proof of work
     */
    static proofOfWork(challenge: string, difficulty?: number): Promise<{
        nonce: string;
        hash: string;
        attempts: number;
    }>;
}

/**
 * Hash security features - security implementations
 */

declare class HashSecurity {
    private static readonly DEFAULT_PBKDF2_ITERATIONS;
    private static readonly DEFAULT_MEMORY_COST;
    private static readonly QUANTUM_SALT_SIZE;
    private static readonly HSM_KEY_SIZE;
    /**
     * Hardware Security Module (HSM) compatible hashing
     * Production implementation using standard cryptographic practices
     */
    static hsmCompatibleHash(input: string | Uint8Array, options?: HSMHashOptions): string | Buffer;
    /**
     * Derive HSM-compatible key using production-grade key derivation
     */
    private static deriveHSMKey;
    /**
     * Verify HSM integrity using cryptographic verification
     */
    private static verifyHSMIntegrity;
    /**
     * Validate hash format and content
     */
    private static isValidHashFormat;
    /**
     * Enhanced security monitoring with real threat detection
     */
    static monitorHashSecurity(operation: string, data: HashOperationData): HashMonitoringResult;
    /**
     * Optimized timing-safe hashing with constant-time operations
     */
    static timingSafeHash(input: string | Uint8Array, options?: {
        algorithm?: string;
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "buffer";
        targetTime?: number;
    }): string | Buffer;
    /**
     * Memory-hard hashing using Argon2
     */
    static memoryHardHash(input: string | Uint8Array, options?: {
        memoryCost?: number;
        timeCost?: number;
        parallelism?: number;
        hashLength?: number;
        salt?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "buffer";
    }): Promise<string | Buffer>;
    /**
     * Quantum-resistant hashing with multiple algorithms
     */
    static quantumResistantHash(input: string | Uint8Array, options?: {
        algorithms?: string[];
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        outputFormat?: "hex" | "base64" | "buffer";
    }): string | Buffer;
    /**
     * Map algorithm names to Node.js crypto algorithms
     */
    private static mapToNodeAlgorithm;
    /**
     * Enhanced secure verification with multiple protection layers
     */
    static secureVerify(input: string | Uint8Array, expectedHash: string | Buffer, options?: {
        algorithm?: string;
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        constantTime?: boolean;
    }): boolean;
    /**
     * Optimized manual constant-time comparison with early termination protection
     */
    private static manualConstantTimeCompare;
    /**
     * Utility method for secure random salt generation with quantum resistance
     */
    static generateQuantumSafeSalt(length?: number): Buffer;
    /**
     * Batch hash verification for improved performance
     */
    static batchVerify(inputs: Array<{
        input: string | Uint8Array;
        expectedHash: string | Buffer;
    }>, options?: {
        algorithm?: string;
        iterations?: number;
        salt?: string | Buffer | Uint8Array;
        constantTime?: boolean;
    }): boolean[];
}

/**
 * Hash advanced features - Optimized hash implementations
 */

declare class HashAdvanced {
    private static readonly CHUNK_SIZE;
    private static readonly MAX_WORKERS;
    /**
     * Cryptographic agility - support for algorithm migration
     * @param input - Input to hash
     * @param options - Migration options
     * @returns Hash with algorithm metadata
     */
    static agilityHash(input: string | Uint8Array, options?: AgilityHashOptions): HashAgilityResult;
    /**
     * Side-channel attack resistant hashing
     * @param input - Input to hash
     * @param options - Resistance options
     * @returns Side-channel resistant hash
     */
    static sideChannelResistantHash(input: string | Uint8Array, options?: SideChannelOptions): string | Buffer;
    /**
     * Constant-time hash processing
     * @param inputBuffer - Input buffer
     * @param memoryProtection - Enable memory protection
     * @param outputFormat - Output format
     * @returns Constant-time hash
     */
    private static constantTimeHash;
    /**
     * Power analysis resistant hash processing - optimized implementation
     * @param inputBuffer - Input buffer
     * @param outputFormat - Output format
     * @returns Power analysis resistant hash
     */
    private static powerAnalysisResistantHash;
    /**
     * tse.ExecutionResultparallel hash processing using worker threads
     * @param input - Input to hash
     * @param options - Parallel processing options
     * @returns Promise resolving to hash result
     */
    static parallelHash(input: string | Uint8Array, options?: {
        chunkSize?: number;
        workers?: number;
        algorithm?: string;
        outputFormat?: "hex" | "base64" | "buffer";
    }): Promise<string | Buffer>;
    /**
     * Optimized streaming hash for large data processing
     * @param algorithm - Hash algorithm
     * @param options - Streaming options
     * @returns Stream hash processor
     */
    static createStreamingHash(algorithm?: string, options?: {
        chunkSize?: number;
        progressCallback?: (processed: number, total?: number) => void;
    }): {
        update: (chunk: Buffer) => void;
        digest: () => Buffer;
        reset: () => void;
        getProgress: () => {
            processed: number;
            chunks: number;
        };
    };
    /**
     * Optimized Merkle tree hash for data integrity
     * @param data - Array of data chunks
     * @param algorithm - Hash algorithm
     * @returns Merkle root hash
     */
    static merkleTreeHash(data: (string | Uint8Array | Buffer)[], algorithm?: string): Buffer;
    /**
     * Optimized incremental hash for append-only data
     * @param previousHash - Previous hash state
     * @param newData - New data to append
     * @param algorithm - Hash algorithm
     * @returns Updated hash
     */
    static incrementalHash(previousHash: string | Buffer, newData: string | Uint8Array | Buffer, algorithm?: string): Buffer;
    /**
     * Optimized hash chain for sequential data integrity
     * @param data - Array of data items
     * @param algorithm - Hash algorithm
     * @returns Array of chained hashes
     */
    static hashChain(data: (string | Uint8Array | Buffer)[], algorithm?: string): Buffer[];
    /**
     * Batch hash processing for multiple inputs
     * @param inputs - Array of inputs to hash
     * @param algorithm - Hash algorithm
     * @param outputFormat - Output format
     * @returns Array of hashes
     */
    static batchHash(inputs: (string | Uint8Array | Buffer)[], algorithm?: string, outputFormat?: "hex" | "base64" | "buffer"): (string | Buffer)[];
    /**
     * Memory-efficient hash verification
     * @param input - Input to verify
     * @param expectedHash - Expected hash value
     * @param algorithm - Hash algorithm
     * @returns True if hash matches
     */
    static verifyHash(input: string | Uint8Array | Buffer, expectedHash: string | Buffer, algorithm?: string): boolean;
}

/**
 * Hash entropy analysis and quality assessment
 */

declare class HashEntropy {
    /**
     * Advanced entropy analysis for hash quality assessment
     * @param data - Data to analyze
     * @returns Entropy analysis results
     */
    static analyzeHashEntropy(data: Buffer | Uint8Array): HashEntropyAnalysis;
    /**
     * Perform statistical randomness tests
     * @param data - Data to test
     * @returns Test results
     */
    static performRandomnessTests(data: Buffer): {
        monobitTest: {
            passed: boolean;
            score: number;
        };
        runsTest: {
            passed: boolean;
            score: number;
        };
        frequencyTest: {
            passed: boolean;
            score: number;
        };
        serialTest: {
            passed: boolean;
            score: number;
        };
        overallScore: number;
    };
    /**
     * Monobit test - checks balance of 0s and 1s
     * @param data - Data to test
     * @returns Test result
     */
    private static monobitTest;
    /**
     * Runs test - checks for proper distribution of runs
     * @param data - Data to test
     * @returns Test result
     */
    private static runsTest;
    /**
     * Frequency test - checks distribution of byte values
     * @param data - Data to test
     * @returns Test result
     */
    private static frequencyTest;
    /**
     * Serial test - checks correlation between consecutive bytes
     * @param data - Data to test
     * @returns Test result
     */
    private static serialTest;
    /**
     * Estimate entropy rate of data
     * @param data - Data to analyze
     * @returns Entropy rate in bits per byte
     */
    static estimateEntropyRate(data: Buffer): number;
    /**
     * Generate entropy quality report
     * @param data - Data to analyze
     * @returns Comprehensive entropy report
     */
    static generateEntropyReport(data: Buffer): {
        analysis: HashEntropyAnalysis;
        randomnessTests: ReturnType<typeof HashEntropy.performRandomnessTests>;
        entropyRate: number;
        recommendations: string[];
        overallGrade: "POOR" | "FAIR" | "GOOD" | "EXCELLENT";
    };
}

/**
 * Hash Core - Main Hash class with modular architecture
 * This is the primary interface for all hashing operations
 */

/**
 * Military-grade hashing functionality with enhanced security features
 * Modular architecture for maintainable and scalable hash operations
 */
declare class Hash {
    /**
     * Create secure hash with military-grade security options
     *
     * IMPORTANT: This method automatically generates a random salt
     * when no salt is provided, resulting in different hashes for the same input.
     * This is designed for password hashing where randomness enhances security.
     *
     * For consistent hashes, either:
     * - Provide a fixed salt parameter, or
     * - Use Hash.create() method instead
     *
     * @param input - The input to hash
     * @param salt - Salt for the hash (if not provided, random salt is auto-generated)
     * @param options - Enhanced hashing options
     * @returns The hash in the specified format
     */
    static createSecureHash(input: string | Uint8Array, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): string | Promise<string>;
    /**
     * Verify hash with secure comparison
     * @param input - Input to verify
     * @param expectedHash - Expected hash value
     * @param salt - Salt used in original hash
     * @param options - Verification options
     * @returns True if hash matches
     */
    static verifyHash(input: string | Uint8Array, expectedHash: string | Buffer, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): boolean;
    /**
     * Async verify hash with secure comparison
     * @param input - Input to verify
     * @param expectedHash - Expected hash value
     * @param salt - Salt used in original hash
     * @param options - Verification options
     * @returns Promise resolving to true if hash matches
     */
    static verifyHashAsync(input: string | Uint8Array, expectedHash: string | Buffer, salt?: string | Buffer | Uint8Array, options?: EnhancedHashOptions): Promise<boolean>;
    /**
     * Enhanced PBKDF2 key derivation
     */
    static deriveKeyPBKDF2: typeof HashSecurity.memoryHardHash;
    /**
     * Enhanced scrypt key derivation
     */
    static deriveKeyScrypt(password: string | Buffer, salt: string | Buffer, keyLength?: number, options?: {
        N?: number;
        r?: number;
        p?: number;
        encoding?: "hex" | "base64" | "buffer";
        validateStrength?: boolean;
    }): string | Buffer;
    /**
     * Enhanced Argon2 key derivation
     */
    static deriveKeyArgon2: typeof HashSecurity.memoryHardHash;
    /**
     * Standard PBKDF2 key derivation
     *
     * BEHAVIOR: Uses Node.js crypto.pbkdf2Sync for reliable, standard PBKDF2 implementation.
     * Produces consistent results and is widely compatible.
     * With crypto:
     * @example
     * crypto.pbkdf2Sync(
            password,
            salt,
            iterations,
            keyLength,
            hashFunction
        );
     *
     * @param password - Password to derive key from
     * @param salt - Salt for the derivation
     * @param iterations - Number of iterations (default: 100000)
     * @param keyLength - Desired key length in bytes (default: 32)
     * @param hashFunction - Hash function to use (default: "sha256")
     * @param outputFormat - Output format (default: "hex")
     * @returns PBKDF2 derived key
     */
    static pbkdf2(password: string, salt: string, iterations?: number, keyLength?: number, hashFunction?: "sha256" | "sha512", outputFormat?: "hex" | "base64" | "buffer"): string | Buffer;
    /**
     * Hardware Security Module (HSM) compatible hashing
     */
    static hsmCompatibleHash: typeof HashSecurity.hsmCompatibleHash;
    /**
     * Cryptographic agility hash
     */
    static agilityHash: typeof HashAdvanced.agilityHash;
    /**
     * Side-channel attack resistant hashing
     */
    static sideChannelResistantHash: typeof HashAdvanced.sideChannelResistantHash;
    /**
     * Real-time security monitoring
     */
    static monitorHashSecurity: typeof HashSecurity.monitorHashSecurity;
    /**
     * Analyze hash entropy
     */
    static analyzeHashEntropy: typeof HashEntropy.analyzeHashEntropy;
    /**
     * Generate entropy report
     */
    static generateEntropyReport: typeof HashEntropy.generateEntropyReport;
    /**
     * Perform randomness tests
     */
    static performRandomnessTests: typeof HashEntropy.performRandomnessTests;
    /**
     * Validate password strength
     */
    static validatePasswordStrength: typeof HashValidator.validatePasswordStrength;
    /**
     * Timing-safe string comparison
     */
    static timingSafeEqual: typeof HashValidator.timingSafeEqual;
    /**
     * Validate salt quality
     */
    static validateSalt: typeof HashValidator.validateSalt;
    /**
     * Parallel hash processing
     */
    static parallelHash: typeof HashAdvanced.parallelHash;
    /**
     * Streaming hash for large data
     */
    static createStreamingHash: typeof HashAdvanced.createStreamingHash;
    /**
     * Merkle tree hash
     */
    static merkleTreeHash: typeof HashAdvanced.merkleTreeHash;
    /**
     * Incremental hash
     */
    static incrementalHash: typeof HashAdvanced.incrementalHash;
    /**
     * Hash chain
     */
    static hashChain: typeof HashAdvanced.hashChain;
    /**
     * Format hash output
     */
    static formatOutput: typeof HashUtils.formatOutput;
    /**
     * Get strength configuration
     */
    static getStrengthConfiguration: typeof HashUtils.getStrengthConfiguration;
    /**
     * Get algorithm security level
     */
    static getAlgorithmSecurityLevel: typeof HashUtils.getAlgorithmSecurityLevel;
    /**
     * Handle secure wipe if requested
     * IMPORTANT: Only wipe copies, not the original salt/pepper that might be needed for verification
     */
    private static handleSecureWipe;
    /**
     * Legacy secure hash method (for backward compatibility)
     *
     * BEHAVIOR: Produces consistent hashes for the same input (like CryptoJS).
     * This method does NOT auto-generate random salts, ensuring deterministic results.
     *
     * For password hashing with auto-salt generation, use Hash.createSecureHash() instead.
     */
    static create: typeof HashAlgorithms.secureHash;
    /**
     * Legacy HMAC creation (for backward compatibility)
     */
    static createSecureHMAC: typeof HashAlgorithms.createSecureHMAC;
}

/**
 * Random types - Type definitions and interfaces for random operations
 */

type EncodingHashType = "hex" | "base64" | "base58" | "buffer";
declare enum RNGState {
    UNINITIALIZED = "uninitialized",
    INITIALIZING = "initializing",
    READY = "ready",
    ERROR = "error",
    RESEEDING = "reseeding"
}
declare enum EntropyQuality {
    POOR = "poor",
    FAIR = "fair",
    GOOD = "good",
    EXCELLENT = "excellent",
    MILITARY = "military"
}
interface SodiumInterface {
    ready: Promise<void> | boolean;
    randombytes_buf: (size: number) => Uint8Array;
    crypto_secretbox_NONCEBYTES: number;
    crypto_secretbox_KEYBYTES: number;
    crypto_aead_chacha20poly1305_ietf_encrypt: (message: Uint8Array, additionalData: Uint8Array | null, secretNonce: Uint8Array | null, publicNonce: Uint8Array, key: Uint8Array) => Uint8Array;
    crypto_aead_chacha20poly1305_ietf_decrypt: (secretNonce: Uint8Array | null, ciphertext: Uint8Array, additionalData: Uint8Array | null, publicNonce: Uint8Array, key: Uint8Array) => Uint8Array;
}
interface ForgeInterface {
    random: {
        getBytesSync: (count: number) => string;
    };
}
interface SecureRandomInterface {
    randomBytes?: (size: number) => Uint8Array;
    (size: number): Uint8Array;
}
interface RandomBytesInterface {
    (size: number): Buffer;
}
interface TweetNaClInterface {
    randomBytes: (size: number) => Uint8Array;
}
interface NobleHashesInterface {
    sha256: (data: Uint8Array) => Uint8Array;
    sha512: (data: Uint8Array) => Uint8Array;
    blake3?: (data: Uint8Array) => Uint8Array;
}
interface RandomGenerationOptions {
    useEntropyPool?: boolean;
    quantumSafe?: boolean;
    reseedThreshold?: number;
    securityLevel?: SecurityLevel$1;
    validateOutput?: boolean;
}
interface EntropySourceConfig {
    name: string;
    enabled: boolean;
    priority: number;
    fallbackAvailable: boolean;
    lastUsed?: number;
    errorCount?: number;
}
interface QuantumSafeOptions$1 {
    enabled: boolean;
    algorithm?: "kyber" | "dilithium" | "falcon";
    keySize?: number;
    additionalEntropy?: boolean;
}
interface TokenGenerationOptions {
    includeUppercase?: boolean;
    includeLowercase?: boolean;
    includeNumbers?: boolean;
    includeSymbols?: boolean;
    excludeSimilarCharacters?: boolean;
    entropyLevel?: SecurityLevel$1;
    outputFormat?: EncodingHashType;
    customCharset?: string;
    minEntropy?: number;
}
interface IVGenerationOptions {
    algorithm?: "aes-128-cbc" | "aes-192-cbc" | "aes-256-cbc" | "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm" | "aes-128-ctr" | "aes-192-ctr" | "aes-256-ctr" | "chacha20" | "chacha20-poly1305" | "des-ede3-cbc" | "blowfish-cbc";
    quantumSafe?: boolean;
    useEntropyPool?: boolean;
    validateSize?: boolean;
}
interface CryptoUtilityOptions {
    keySize?: number;
    algorithm?: string;
    quantumSafe?: boolean;
    useHardwareEntropy?: boolean;
    validateStrength?: boolean;
}
interface SecurityMonitoringResult {
    entropyQuality: EntropyQuality;
    securityLevel: SecurityLevel$1;
    threats: string[];
    recommendations: string[];
    timestamp: number;
    bytesGenerated: number;
    reseedCount: number;
    libraryStatus: Record<string, boolean>;
}
interface EntropyAnalysisResult$1 {
    shannonEntropy: number;
    minEntropy: number;
    compressionRatio: number;
    randomnessScore: number;
    qualityGrade: EntropyQuality;
    recommendations: string[];
    testResults: {
        monobitTest: {
            passed: boolean;
            score: number;
        };
        runsTest: {
            passed: boolean;
            score: number;
        };
        frequencyTest: {
            passed: boolean;
            score: number;
        };
        serialTest: {
            passed: boolean;
            score: number;
        };
    };
}
interface LibraryStatus extends Record<string, boolean> {
    sodium: boolean;
    forge: boolean;
    secureRandom: boolean;
    randombytes: boolean;
    nobleHashes: boolean;
    tweetnacl: boolean;
    kyber: boolean;
    entropyString: boolean;
    cryptoJs: boolean;
    elliptic: boolean;
    nobleCurves: boolean;
}
interface RandomState {
    entropyPool: Buffer;
    lastReseed: number;
    state: RNGState;
    bytesGenerated: number;
    entropyQuality: EntropyQuality;
    securityLevel: SecurityLevel$1;
    quantumSafeMode: boolean;
    reseedCounter: number;
    hardwareEntropyAvailable: boolean;
    sidechannelProtection: boolean;
    entropyAugmentation: boolean;
    realTimeMonitoring: boolean;
    lastEntropyTest: number;
    entropyTestResults: Map<string, number>;
    securityAlerts: string[];
    additionalEntropySources: Map<string, () => Buffer>;
}
type EntropySourceFunction = () => Buffer;
type SecurityValidator = (data: Uint8Array) => boolean;
type EntropyCollector = (size: number) => Buffer;
interface AlgorithmConfig {
    name: string;
    keySize: number;
    ivSize: number;
    blockSize: number;
    securityLevel: SecurityLevel$1;
    quantumResistant: boolean;
}
interface CipherConfig extends AlgorithmConfig {
    mode: "cbc" | "gcm" | "ctr" | "ecb";
    authTagLength?: number;
    nonceSize?: number;
}
type RandomOptions = RandomGenerationOptions & QuantumSafeOptions$1 & CryptoUtilityOptions;
type AllRandomTypes = RandomState & SecurityMonitoringResult & EntropyAnalysisResult$1;

type EncodingType = "hex" | "base64" | "base64url" | "base58" | "binary" | "utf8" | BaseEncodingType;

/**
 * Enhanced Uint8Array with encoding support and improved security
 */
declare class EnhancedUint8Array extends Uint8Array {
    private _isCleared;
    /**
     * Convert to string with specified encoding
     * @param encoding - Encoding type (optional, defaults to hex for security)
     * @returns Encoded string
     */
    toString(encoding?: EncodingType): string;
    /**
     * Secure hex conversion
     */
    private _toHexSecure;
    /**
     * Secure base64 conversion
     */
    private _toBase64Secure;
    /**
     * Secure Base58 conversion with improved error handling
     */
    private _toBase58Secure;
    /**
     * Secure binary conversion
     */
    private _toBinarySecure;
    /**
     * Secure UTF-8 conversion
     */
    private _toUtf8Secure;
    /**
     * Get entropy information with enhanced analysis
     */
    getEntropyInfo(): {
        bytes: number;
        bits: number;
        quality: string;
        entropy: number;
    };
    /**
     * Calculate Shannon entropy for quality assessment
     */
    private _calculateShannonEntropy;
    /**
     * Get quality rating based on entropy and length
     */
    private _getQualityRating;
    /**
     * Get as Buffer with proper typing and security
     * @returns Buffer<ArrayBufferLike> containing the same data
     */
    getBuffer(): Buffer<ArrayBufferLike>;
    /**
     * Securely clear the array contents
     */
    clear(): void;
    /**
     * Check if array has been cleared
     */
    private _checkCleared;
    /**
     * Create a secure copy of the array
     */
    secureClone(): EnhancedUint8Array;
    /**
     * Compare with another array in constant time to prevent timing attacks
     */
    constantTimeEquals(other: Uint8Array): boolean;
    /**
     * Convert to regular Uint8Array for safe Buffer operations
     */
    toUint8Array(): Uint8Array;
    /**
     * Override valueOf to provide safe primitive conversion
     * Returns this instance for Buffer.from() compatibility
     */
    valueOf(): this;
}

/**
 * ## Core Cryptographic Exports
 *
 * Primary cryptographic classes and utilities for secure random generation,
 * key management, validation, and buffer operations.
 */
/**
 * ### Secure Random Generation
 *
 * High-entropy random number and data generation with multiple entropy sources.
 * Provides cryptographically secure random values for all security operations.
 *
 * @example
 * ```typescript
 * import { Random } from "xypriss-security";
 *
 * // Generate secure random bytes
 * const randomBytes = Random.getRandomBytes(32);
 *
 * // Generate secure UUID
 * const uuid = Random.generateSecureUUID();
 *
 * // Generate random integers
 * const randomInt = Random.getSecureRandomInt(1, 100);
 * ```
 */
declare class SecureRandom {
    private static instance;
    private state;
    private stats;
    private constructor();
    /**
     * Get singleton instance
     */
    static getInstance(): SecureRandom;
    /**
     * Initialize entropy pool
     */
    private initializeEntropyPool;
    /**
     * Setup additional entropy sources
     */
    private setupAdditionalEntropySources;
    /**
     * Detect hardware entropy availability
     */
    private detectHardwareEntropy;
    /**
     * Generate ultra-secure random bytes with enhanced entropy
     * @param length - Number of bytes to generate
     * @param options - Generation options
     * @returns Enhanced random bytes
     */
    static getRandomBytes(length: number, options?: RandomGenerationOptions): EnhancedUint8Array;
    /**
     * Get system random bytes (fallback method)
     */
    static getSystemRandomBytes(length: number): Uint8Array;
    /**
     * Generate secure random integer
     */
    static getSecureRandomInt(min: number, max: number, options?: RandomGenerationOptions): number;
    /**
     * Generate secure UUID v4
     */
    static generateSecureUUID(options?: RandomGenerationOptions): string;
    /**
     * Generate secure random float
     */
    static getSecureRandomFloat(options?: RandomGenerationOptions): number;
    /**
     * Generate secure random boolean
     */
    static getSecureRandomBoolean(options?: RandomGenerationOptions): boolean;
    /**
     * Generate salt
     */
    static generateSalt(length?: number, options?: RandomGenerationOptions): Buffer;
    /**
     * Reseed entropy pool
     */
    reseedEntropyPool(): void;
    /**
     * Get entropy analysis
     */
    static getEntropyAnalysis(data?: Buffer): EntropyAnalysisResult$1;
    /**
     * Assess entropy quality
     */
    static assessEntropyQuality(data: Buffer): EntropyQuality;
    /**
     * Get security monitoring result
     */
    static getSecurityStatus(): SecurityMonitoringResult;
    /**
     * Get library status
     */
    static getLibraryStatus(): LibraryStatus;
    /**
     * Check if secure random is available
     */
    static isSecureRandomAvailable(): boolean;
    /**
     * Get current state
     */
    getState(): RandomState;
    /**
     * Get statistics
     */
    static getStatistics(): {
        bytesGenerated: number;
        reseedCount: number;
        lastReseed: number;
        entropyQuality: EntropyQuality;
        state: RNGState;
    };
    /**
     * Reset instance (for testing)
     */
    static resetInstance(): void;
    /**
     * Enable quantum-safe mode
     */
    static enableQuantumSafeMode(): void;
    /**
     * Disable quantum-safe mode
     */
    static disableQuantumSafeMode(): void;
    /**
     * Set security level
     */
    static setSecurityLevel(level: SecurityLevel$1): void;
}

/**
 * Random entropy - Entropy pool management and quality assessment
 */

declare class RandomEntropy {
    /**
     * Initialize entropy pool with multiple sources
     */
    static initializeEntropyPool(poolSize?: number): Promise<Buffer>;
    /**
     * Gather secondary entropy from various sources
     */
    static gatherSecondaryEntropy(): Promise<Buffer>;
    /**
     * Get high-resolution timing entropy
     */
    static getTimingEntropy(): Buffer;
    /**
     * Get memory usage entropy
     */
    static getMemoryEntropy(): Buffer;
    /**
     * Get process entropy
     */
    static getProcessEntropy(): Buffer;
    /**
     * Get async timing entropy with delays
     */
    static getAsyncTimingEntropy(): Promise<Buffer>;
    /**
     * Assess entropy quality of data
     */
    static assessEntropyQuality(data: Buffer): EntropyQuality;
    /**
     * Perform comprehensive entropy analysis
     */
    static analyzeEntropy(data: Buffer): EntropyAnalysisResult$1;
    /**
     * Perform statistical randomness tests
     */
    static performStatisticalTests(data: Buffer): {
        monobitTest: {
            passed: boolean;
            score: number;
        };
        runsTest: {
            passed: boolean;
            score: number;
        };
        frequencyTest: {
            passed: boolean;
            score: number;
        };
        serialTest: {
            passed: boolean;
            score: number;
        };
    };
    /**
     * Monobit test - checks balance of 0s and 1s
     */
    private static monobitTest;
    /**
     * Runs test - checks for proper distribution of runs
     */
    private static runsTest;
    /**
     * Frequency test - checks distribution of byte values
     */
    private static frequencyTest;
    /**
     * Serial test - checks correlation between consecutive bytes
     */
    private static serialTest;
    /**
     * Reseed entropy pool with fresh entropy
     */
    static reseedEntropyPool(currentPool: Buffer): Promise<Buffer>;
}

/**
 * Random sources - Multiple entropy sources and library management
 */

declare class RandomSources {
    private static initialized;
    private static initializationPromise;
    /**
     * Initialize all security libraries with comprehensive error handling
     */
    static initializeLibraries(): Promise<void>;
    private static performInitialization;
    private static initializeSodium;
    private static initializeForge;
    private static initializeSecureRandom;
    private static initializeRandomBytes;
    private static initializeNobleHashes;
    private static initializeTweetNaCl;
    private static initializeAdditionalLibraries;
    /**
     * Get system entropy from multiple CSPRNG sources (military-grade)
     */
    static getSystemEntropy(size: number): Buffer;
    /**
     * Cryptographically combine multiple entropy sources
     */
    static combineEntropySources(sources: Buffer[], targetSize: number): Buffer;
    /**
     * Get fallback entropy when all other sources fail
     */
    static getFallbackEntropy(size: number): Buffer;
    /**
     * Get library status
     */
    static getLibraryStatus(): LibraryStatus;
    /**
     * Get available entropy sources
     */
    static getAvailableEntropySources(): EntropySourceConfig[];
    /**
     * Test entropy source availability
     */
    static testEntropySource(sourceName: string): boolean;
}

/**
 * Random generators - Core random generation methods (bytes, ints, UUIDs)
 */

declare class RandomGenerators {
    /**
     * Generate cryptographically secure random bytes
     * @param length - Number of bytes to generate
     * @param options - Generation options
     * @returns Secure random bytes
     */
    static getRandomBytes(length: number, options?: RandomGenerationOptions): Uint8Array;
    /**
     * Get system random bytes using multiple sources
     */
    static getSystemRandomBytes(length: number): Uint8Array;
    /**
     * Get quantum-safe random bytes
     */
    static getQuantumSafeBytes(length: number): Uint8Array;
    /**
     * Fallback random bytes (not cryptographically secure)
     */
    static getFallbackRandomBytes(length: number): Uint8Array;
    /**
     * Validate random output quality
     */
    static validateRandomOutput(bytes: Uint8Array): void;
    /**
     * Generate cryptographically secure random integers with uniform distribution
     * @param min - Minimum value (inclusive)
     * @param max - Maximum value (inclusive)
     * @param options - Generation options
     * @returns Secure random integer
     */
    static getSecureRandomInt(min: number, max: number, options?: RandomGenerationOptions): number;
    /**
     * Generate random integer for small ranges (≤256)
     */
    private static getSmallRangeInt;
    /**
     * Generate random integer for large ranges (>256)
     */
    private static getLargeRangeInt;
    /**
     * Generate secure UUID v4
     * @param options - Generation options
     * @returns Secure UUID string
     */
    static generateSecureUUID(options?: RandomGenerationOptions): string;
    /**
     * Generate multiple UUIDs efficiently
     * @param count - Number of UUIDs to generate
     * @param options - Generation options
     * @returns Array of secure UUID strings
     */
    static generateSecureUUIDBatch(count: number, options?: RandomGenerationOptions): string[];
    /**
     * Generate random float between 0 and 1
     * @param options - Generation options
     * @returns Secure random float
     */
    static getSecureRandomFloat(options?: RandomGenerationOptions): number;
    /**
     * Generate random boolean
     * @param options - Generation options
     * @returns Secure random boolean
     */
    static getSecureRandomBoolean(options?: RandomGenerationOptions): boolean;
    /**
     * Generate random choice from array
     * @param array - Array to choose from
     * @param options - Generation options
     * @returns Random element from array
     */
    static getSecureRandomChoice<T>(array: T[], options?: RandomGenerationOptions): T;
    /**
     * Shuffle array using Fisher-Yates algorithm with secure randomness
     * @param array - Array to shuffle
     * @param options - Generation options
     * @returns Shuffled array (new array)
     */
    static secureArrayShuffle<T>(array: T[], options?: RandomGenerationOptions): T[];
    /**
     * Generate salt with specified length
     * @param length - Salt length in bytes
     * @param options - Generation options
     * @returns Salt as Buffer
     */
    static generateSalt(length?: number, options?: RandomGenerationOptions): Buffer;
    /**
     * Generate nonce with specified length
     * @param length - Nonce length in bytes
     * @param options - Generation options
     * @returns Nonce as EnhancedUint8Array
     */
    static generateNonce(length?: number, options?: RandomGenerationOptions): EnhancedUint8Array;
}

/**
 * Random tokens - Token and password generation utilities
 */

declare class RandomTokens {
    /**
     * Generate a secure token with specified options
     * @param length - Length of the token
     * @param options - Token generation options
     * @returns Secure random token
     */
    static generateSecureToken(length: number, options?: TokenGenerationOptions): string;
    /**
     * Generate secure password with complexity requirements
     * @param length - Password length
     * @param options - Generation options
     * @returns Secure password
     */
    static generateSecurePassword(length?: number, options?: TokenGenerationOptions): string;
    /**
     * Generate session token
     * @param length - Token length in bytes
     * @param encoding - Output encoding
     * @param options - Generation options
     * @returns Secure session token
     */
    static generateSessionToken(length?: number, encoding?: "hex" | "base64" | "base64url", options?: RandomGenerationOptions): string;
    /**
     * Generate API key
     * @param length - Key length
     * @param prefix - Optional prefix
     * @param options - Generation options
     * @returns Secure API key
     */
    static generateAPIKey(length?: number, prefix?: string, options?: TokenGenerationOptions): string;
    /**
     * Generate secure PIN
     * @param length - PIN length
     * @param options - Generation options
     * @returns Secure numeric PIN
     */
    static generateSecurePIN(length?: number, options?: RandomGenerationOptions): string;
    /**
     * Generate secure OTP (One-Time Password)
     * @param length - OTP length
     * @param options - Generation options
     * @returns Secure OTP
     */
    static generateSecureOTP(length?: number, options?: TokenGenerationOptions): string;
    /**
     * Generate recovery codes
     * @param count - Number of codes to generate
     * @param codeLength - Length of each code
     * @param options - Generation options
     * @returns Array of recovery codes
     */
    static generateRecoveryCodes(count?: number, codeLength?: number, options?: TokenGenerationOptions): string[];
    /**
     * Get random character from character set
     */
    private static getRandomCharFromSet;
    /**
     * Build character set based on options
     */
    private static buildCharset;
    /**
     * Validate token strength
     * @param token - Token to validate
     * @returns Strength assessment
     */
    static validateTokenStrength(token: string): {
        score: number;
        strength: "weak" | "fair" | "good" | "strong" | "excellent";
        issues: string[];
    };
}

/**
 * Random crypto - Cryptographic utilities (IV, keys, nonces)
 */

declare class RandomCrypto {
    /**
     * Generate secure nonce/IV for encryption
     * @param algorithm - Algorithm requiring the nonce
     * @param options - Generation options
     * @returns Nonce as Uint8Array
     */
    static generateNonce(algorithm: "aes-gcm" | "chacha20-poly1305" | "aes-cbc" | "custom", options?: {
        quantumSafe?: boolean;
        useEntropyPool?: boolean;
        customLength?: number;
    }): Uint8Array;
    /**
     * Generate a secure Initialization Vector (IV) for encryption algorithms
     * @param length - Length of the IV in bytes
     * @param options - Generation options including algorithm
     * @returns Secure IV as EnhancedUint8Array
     */
    static generateSecureIV(length: number, options?: IVGenerationOptions): EnhancedUint8Array;
    /**
     * Generate multiple IVs efficiently
     * @param count - Number of IVs to generate
     * @param length - Length of each IV
     * @param options - Generation options
     * @returns Array of IVs
     */
    static generateSecureIVBatch(count: number, length: number, options?: IVGenerationOptions): EnhancedUint8Array[];
    /**
     * Generate IV for specific algorithm
     * @param algorithm - Encryption algorithm
     * @param options - Generation options
     * @returns Algorithm-specific IV
     */
    static generateSecureIVForAlgorithm(algorithm: string, options?: IVGenerationOptions): EnhancedUint8Array;
    /**
     * Generate multiple IVs for specific algorithm
     * @param count - Number of IVs to generate
     * @param algorithm - Encryption algorithm
     * @param options - Generation options
     * @returns Array of algorithm-specific IVs
     */
    static generateSecureIVBatchForAlgorithm(count: number, algorithm: string, options?: IVGenerationOptions): EnhancedUint8Array[];
    /**
     * Validate IV for algorithm
     * @param iv - IV to validate
     * @param algorithm - Target algorithm
     * @returns Validation result
     */
    static validateIV(iv: Uint8Array | Buffer, algorithm: string): {
        valid: boolean;
        expectedLength?: number;
        actualLength: number;
        message: string;
    };
    /**
     * Create secure cipher with auto-generated IV
     * @param algorithm - Cipher algorithm
     * @param key - Encryption key
     * @param options - Cipher options
     * @returns Cipher and IV
     */
    static createSecureCipheriv(algorithm: string, key: crypto__default.CipherKey, options?: CryptoUtilityOptions): {
        cipher: crypto__default.Cipher;
        iv: Buffer;
    };
    /**
     * Create secure decipher
     * @param algorithm - Cipher algorithm
     * @param key - Decryption key
     * @param iv - Initialization vector
     * @returns Decipher
     */
    static createSecureDecipheriv(algorithm: string, key: crypto__default.CipherKey, iv: crypto__default.BinaryLike): crypto__default.Decipher;
    /**
     * Generate cryptographic key
     * @param length - Key length in bytes
     * @param options - Generation options
     * @returns Cryptographic key
     */
    static generateCryptoKey(length: number, options?: CryptoUtilityOptions): Buffer;
    /**
     * Validate key strength
     * @param key - Key to validate
     * @returns Validation result
     */
    static validateKeyStrength(key: Buffer): {
        valid: boolean;
        strength: "weak" | "fair" | "good" | "strong";
        issues: string[];
    };
    /**
     * Generate key derivation salt
     * @param length - Salt length
     * @param options - Generation options
     * @returns KDF salt
     */
    static generateKDFSalt(length?: number, options?: RandomGenerationOptions): Buffer;
    /**
     * Generate HMAC key
     * @param algorithm - HMAC algorithm
     * @param options - Generation options
     * @returns HMAC key
     */
    static generateHMACKey(algorithm?: string, options?: CryptoUtilityOptions): Buffer;
}

/**
 * Random security - Advanced security features and monitoring
 * Optimized for real-world applications
 */

declare class RandomSecurity {
    private static securityAlerts;
    private static lastSecurityCheck;
    private static threatLevel;
    private static monitoringEnabled;
    private static monitoringInterval;
    /**
     * Perform comprehensive security assessment
     * @param data - Data to assess (optional)
     * @returns Security monitoring result
     */
    static performSecurityAssessment(data?: Buffer): SecurityMonitoringResult;
    /**
     * Assess current threats based on real-world security concerns
     */
    private static assessThreats;
    /**
     * Generate actionable security recommendations
     */
    private static generateRecommendations;
    /**
     * Determine security level based on threat assessment
     */
    private static determineSecurityLevel;
    /**
     * Check if secure random generation is available
     */
    private static isSecureRandomAvailable;
    /**
     * Detect high-frequency usage patterns
     */
    private static detectHighFrequencyUsage;
    /**
     * Update threat level (only escalate, never de-escalate)
     */
    private static updateThreatLevel;
    /**
     * Monitor for side-channel attacks with real-world heuristics
     */
    static monitorSideChannelAttacks(data: Buffer): {
        riskLevel: "low" | "medium" | "high";
        indicators: string[];
        recommendations: string[];
    };
    /**
     * Calculate Shannon entropy for data quality assessment
     */
    private static calculateShannonEntropy;
    /**
     * Validate entropy source integrity
     */
    static validateEntropySourceIntegrity(sourceName: string): {
        valid: boolean;
        confidence: number;
        issues: string[];
    };
    /**
     * Generate comprehensive security report
     */
    static generateSecurityReport(includeDetails?: boolean): {
        summary: string;
        threatLevel: string;
        recommendations: string[];
        details?: any;
    };
    /**
     * Enable security monitoring with configurable interval
     */
    static enableSecurityMonitoring(intervalMs?: number): void;
    /**
     * Disable security monitoring
     */
    static disableSecurityMonitoring(): void;
    /**
     * Get security alerts
     */
    static getSecurityAlerts(): string[];
    /**
     * Clear security alerts
     */
    static clearSecurityAlerts(): void;
    /**
     * Get current threat level
     */
    static getThreatLevel(): "low" | "medium" | "high" | "critical";
    /**
     * Assess quantum readiness with realistic recommendations
     */
    static assessQuantumReadiness(): {
        ready: boolean;
        score: number;
        recommendations: string[];
        algorithms: {
            name: string;
            quantumSafe: boolean;
            available: boolean;
        }[];
    };
    /**
     * Get monitoring status
     */
    static getMonitoringStatus(): {
        enabled: boolean;
        lastCheck: number;
        alertCount: number;
        threatLevel: string;
    };
}

declare enum MemoryProtectionLevel {
    BASIC = "basic",
    ENHANCED = "enhanced",
    MILITARY = "military",
    QUANTUM_SAFE = "quantum_safe"
}
declare enum BufferState {
    UNINITIALIZED = "uninitialized",
    ACTIVE = "active",
    LOCKED = "locked",
    DESTROYED = "destroyed",
    CORRUPTED = "corrupted"
}
interface SecureBufferOptions {
    protectionLevel?: MemoryProtectionLevel;
    enableEncryption?: boolean;
    enableFragmentation?: boolean;
    enableCanaries?: boolean;
    enableObfuscation?: boolean;
    autoLock?: boolean;
    lockTimeout?: number;
    quantumSafe?: boolean;
}

/**
 * This module provides military-grade utilities for securely handling sensitive data in memory:
 * - Secure buffers with advanced protection against memory dumps and swapping
 * - Multiple encryption layers for data at rest in memory
 * - Hardware-level security features when available
 * - Protection against cold boot attacks and memory forensics
 * - Canary tokens for tamper detection
 * - Memory fragmentation and obfuscation techniques
 * - Quantum-resistant security measures
 * - Side-channel attack resistance
 */

declare class SecureBuffer {
    private fragments;
    private encryptionKey;
    private nonce;
    private canaryTokens;
    private canaryPositions;
    private obfuscationMask;
    private state;
    private protectionLevel;
    private options;
    private accessCount;
    private lastAccess;
    private lockTimer;
    private originalSize;
    private checksum;
    /**
     * Creates a new enhanced secure buffer with military-grade protection
     *
     * @param size - Size of the buffer in bytes
     * @param fill - Optional value to fill the buffer with
     * @param options - Security options
     */
    constructor(size: number, fill?: number, options?: SecureBufferOptions);
    /**
     * Initialize the secure buffer with enhanced protection
     */
    private initializeSecureBuffer;
    /**
     * Setup automatic locking mechanism
     */
    private setupAutoLock;
    /**
     * Reset the auto-lock timer
     */
    private resetLockTimer;
    /**
     * Generate a cryptographically secure key
     */
    private generateSecureKey;
    /**
     * Create memory fragments for enhanced security
     */
    private createFragments;
    /**
     * Generate canary tokens for tamper detection and embed them in memory
     */
    private generateCanaryTokens;
    /**
     * Embed canary tokens in memory around buffer fragments
     */
    private embedCanaryInMemory;
    /**
     * Helper method to compare two Uint8Arrays for equality
     */
    private arraysEqual;
    /**
     * Get the unencrypted buffer by combining fragments (extracting data from canary-embedded fragments)
     */
    private getUnencryptedBuffer;
    /**
     * Lock the buffer to prevent access
     */
    lock(): void;
    /**
     * Unlock the buffer to allow access
     */
    unlock(): void;
    /**
     * Check if buffer is locked
     */
    isLocked(): boolean;
    /**
     * Check if buffer is destroyed
     */
    isDestroyed(): boolean;
    /**
     * Verify buffer integrity using canary tokens and checksum
     */
    verifyIntegrity(): boolean;
    /**
     * Encrypt fragments using ChaCha20-Poly1305 or AES-GCM
     */
    private encryptFragments;
    /**
     * Decrypt fragments
     */
    private decryptFragments;
    /**
     * Sets data directly in fragments (private method for initialization)
     *
     * @param data - Data to set in the fragments
     */
    private setDataInFragments;
    /**
     * Creates a secure buffer from existing data
     *
     * @param data - Data to store in the secure buffer
     * @param options - Security options
     * @returns A new secure buffer containing the data
     */
    static from(data: Uint8Array | Array<number> | string, options?: SecureBufferOptions): SecureBuffer;
    /**
     * Gets the underlying buffer (decrypted if necessary)
     * Throws if the buffer has been destroyed or locked
     *
     * @returns The underlying buffer
     */
    getBuffer(): Uint8Array;
    /**
     * Gets the length of the buffer
     *
     * @returns The length of the buffer in bytes
     */
    length(): number;
    /**
     * Copies data to another buffer
     *
     * @param target - Target buffer
     * @param targetStart - Start position in the target buffer
     * @param sourceStart - Start position in this buffer
     * @param sourceEnd - End position in this buffer
     * @returns Number of bytes copied
     */
    copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number;
    /**
     * Fills the buffer with the specified value
     *
     * @param value - Value to fill the buffer with
     * @param start - Start position
     * @param end - End position
     * @returns This buffer
     */
    fill(value: number, start?: number, end?: number): SecureBuffer;
    /**
     * Compares this buffer with another buffer using constant-time comparison
     *
     * @param otherBuffer - Buffer to compare with
     * @returns True if the buffers are equal, false otherwise
     */
    equals(otherBuffer: Uint8Array | SecureBuffer): boolean;
    /**
     * Destroys the buffer by securely wiping its contents
     * After calling this method, the buffer can no longer be used
     */
    destroy(): void;
    /**
     * Get security statistics and information
     */
    getSecurityInfo(): {
        protectionLevel: MemoryProtectionLevel;
        isEncrypted: boolean;
        isFragmented: boolean;
        hasCanaries: boolean;
        isObfuscated: boolean;
        accessCount: number;
        lastAccess: number;
        fragmentCount: number;
        state: BufferState;
    };
    /**
     * Clone the secure buffer with the same protection settings
     */
    clone(): SecureBuffer;
    /**
     * Resize the buffer (creates a new buffer with copied data)
     */
    resize(newSize: number): SecureBuffer;
    /**
     * Update the checksum after buffer modification
     */
    updateChecksum(): void;
    /**
     * Registers a finalizer to clean up the buffer when it's garbage collected
     * This is a best-effort approach as JavaScript doesn't guarantee finalization
     */
    private registerFinalizer;
}
/**
 * Securely wipes a section of memory
 *
 * This implementation follows recommendations from security standards
 * for secure data deletion, using multiple overwrite patterns to ensure
 * data cannot be recovered even with advanced forensic techniques.
 *
 * @param buffer - Buffer to wipe
 * @param start - Start position
 * @param end - End position
 * @param passes - Number of overwrite passes (default: 3)
 */
declare function secureWipe(buffer: Uint8Array, start?: number, end?: number, passes?: number): void;

/**
 * Entropy Augmentation Module
 *
 * This module provides methods to enhance the entropy (randomness) of
 * cryptographic operations by collecting additional entropy from various sources
 * and combining it with the system's built-in random number generator.
 *
 * This helps protect against weak or compromised random number generators
 * by adding multiple layers of entropy.
 */

/**
 * Entropy collection options
 */
interface EntropyOptions {
    /**
     * Whether to collect timing entropy
     * @default true
     */
    useTiming?: boolean;
    /**
     * Whether to collect performance entropy
     * @default true
     */
    usePerformance?: boolean;
    /**
     * Whether to collect device entropy
     * @default true
     */
    useDevice?: boolean;
    /**
     * Whether to collect network entropy
     * @default false
     */
    useNetwork?: boolean;
    /**
     * Whether to collect user interaction entropy
     * @default false
     */
    useInteraction?: boolean;
    /**
     * Custom entropy sources to include
     */
    customSources?: Array<() => Uint8Array>;
}
/**
 * Entropy pool that collects and mixes entropy from multiple sources
 */
declare class EntropyPool {
    private static instance;
    private pool;
    private poolSize;
    private poolPosition;
    private reseedCounter;
    private lastReseed;
    private isInitialized;
    private entropyCollected;
    private options;
    /**
     * Creates a new entropy pool
     *
     * @param poolSize - Size of the entropy pool in bytes
     * @param options - Entropy collection options
     */
    private constructor();
    /**
     * Gets the singleton instance of the entropy pool
     *
     * @param poolSize - Size of the entropy pool in bytes
     * @param options - Entropy collection options
     * @returns The entropy pool instance
     */
    static getInstance(poolSize?: number, options?: EntropyOptions): EntropyPool;
    /**
     * Initializes the entropy pool with system random data
     */
    private initializePool;
    /**
     * Sets up continuous entropy collection from various sources
     */
    private setupEntropyCollection;
    /**
     * Collects entropy from timing variations
     */
    private collectTimingEntropy;
    /**
     * Collects entropy from performance measurements
     */
    private collectPerformanceEntropy;
    /**
     * Collects entropy from device information
     */
    private collectDeviceEntropy;
    /**
     * Collects entropy from network information
     */
    private collectNetworkEntropy;
    /**
     * Sets up collection of entropy from user interactions
     */
    private setupInteractionCollection;
    /**
     * Adds entropy to the pool
     *
     * @param data - Entropy data to add
     * @param estimatedEntropy - Estimated entropy in bits (conservative)
     */
    addEntropy(data: Uint8Array, estimatedEntropy?: number): void;
    /**
     * Remixes the entire entropy pool to distribute entropy
     */
    private remixPool;
    /**
     * Gets random bytes from the entropy pool
     *
     * @param length - Number of bytes to get
     * @returns Random bytes
     */
    getRandomBytes(length: number): Uint8Array;
    /**
     * Gets the current entropy source
     *
     * @returns The current entropy source
     */
    getEntropySource(): EntropySource;
    /**
     * Gets the estimated amount of entropy collected
     *
     * @returns Estimated entropy in bits
     */
    getEstimatedEntropy(): number;
}

/**
 * Log level
 */
declare enum LogLevel$1 {
    DEBUG = "DEBUG",
    INFO = "INFO",
    WARNING = "WARNING",
    ERROR = "ERROR",
    CRITICAL = "CRITICAL"
}
/**
 * Log entry
 */
interface LogEntry {
    /**
     * Unique identifier for the log entry
     */
    id: string;
    /**
     * Timestamp when the log entry was created
     */
    timestamp: number;
    /**
     * Log level
     */
    level: LogLevel$1;
    /**
     * Log message
     */
    message: string;
    /**
     * Additional data
     */
    data?: any;
    /**
     * Hash of the previous log entry
     */
    previousHash: string;
    /**
     * Hash of this log entry
     */
    hash: string;
    /**
     * Sequence number
     */
    sequence: number;
}
/**
 * Log verification result
 */
interface LogVerificationResult {
    /**
     * Whether the log chain is valid
     */
    valid: boolean;
    /**
     * List of invalid entries
     */
    invalidEntries: number[];
    /**
     * List of missing entries
     */
    missingEntries: number[];
    /**
     * List of tampered entries
     */
    tamperedEntries: number[];
}
/**
 * Tamper-evident logger
 */
declare class TamperEvidentLogger {
    private entries;
    private lastHash;
    private sequence;
    private key;
    private storageKey?;
    /**
     * Creates a new tamper-evident logger
     *
     * @param key - Secret key for hashing
     * @param storageKey - Key for storing logs in localStorage (if available)
     */
    constructor(key?: string, storageKey?: string);
    /**
     * Adds a genesis entry to the log
     */
    private addGenesisEntry;
    /**
     * Generates a unique ID for a log entry
     *
     * @returns Unique ID
     */
    private generateId;
    /**
     * Calculates the hash of a log entry
     *
     * @param entry - Log entry to hash
     * @returns Hash of the log entry
     */
    private calculateHash;
    /**
     * Loads logs from storage
     */
    private loadFromStorage;
    /**
     * Saves logs to storage
     */
    private saveToStorage;
    /**
     * Adds a log entry
     *
     * @param level - Log level
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    log(level: LogLevel$1, message: string, data?: any): LogEntry;
    /**
     * Logs a debug message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    debug(message: string, data?: any): LogEntry;
    /**
     * Logs an info message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    info(message: string, data?: any): LogEntry;
    /**
     * Logs a warning message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    warning(message: string, data?: any): LogEntry;
    /**
     * Logs an error message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    error(message: string, data?: any): LogEntry;
    /**
     * Logs a critical message
     *
     * @param message - Log message
     * @param data - Additional data
     * @returns The created log entry
     */
    critical(message: string, data?: any): LogEntry;
    /**
     * Gets all log entries
     *
     * @returns All log entries
     */
    getEntries(): LogEntry[];
    /**
     * Gets log entries by level
     *
     * @param level - Log level
     * @returns Log entries with the specified level
     */
    getEntriesByLevel(level: LogLevel$1): LogEntry[];
    /**
     * Gets log entries by time range
     *
     * @param startTime - Start time
     * @param endTime - End time
     * @returns Log entries within the specified time range
     */
    getEntriesByTimeRange(startTime: number, endTime: number): LogEntry[];
    /**
     * Verifies the integrity of the log chain
     *
     * @returns Verification result
     */
    verify(): LogVerificationResult;
    /**
     * Exports the logs to a string
     *
     * @returns Exported logs
     */
    export(): string;
    /**
     * Imports logs from a string
     *
     * @param data - Exported logs
     * @param verify - Whether to verify the logs after importing
     * @returns Verification result if verify is true
     */
    import(data: string, verify?: boolean): LogVerificationResult | undefined;
    /**
     * Clears all logs
     */
    clear(): void;
}

/**
 * Options for HMAC operations
 */
interface HMACOptions {
    key: string | SecureString | Uint8Array;
    algorithm: HMACAlgorithm;
}
/**
 * Options for PBKDF2 key derivation
 */
interface PBKDF2Options {
    salt: string | Uint8Array;
    iterations: number;
    keyLength: number;
    hash: HashAlgorithm$1;
}
/**
 * Hash output formats
 */
type HashOutputFormat = "hex" | "base64" | "base64url" | "uint8array";
/**
 * Supported cryptographic hash algorithms
 */
type HashAlgorithm$1 = "SHA-1" | "SHA-256" | "SHA-384" | "SHA-512";
/**
 * Supported HMAC algorithms
 */
type HMACAlgorithm = "HMAC-SHA-1" | "HMAC-SHA-256" | "HMAC-SHA-384" | "HMAC-SHA-512";
/**
 * Supported key derivation algorithms
 */
type KDFAlgorithm = "PBKDF2" | "HKDF";
/**
 * All supported cryptographic algorithms
 */
type CryptoAlgorithm = HashAlgorithm$1 | HMACAlgorithm | KDFAlgorithm;
/**
 * Algorithm metadata including output size and security level
 */
interface AlgorithmInfo {
    readonly name: string;
    readonly outputSize: number;
    readonly securityLevel: "weak" | "acceptable" | "strong" | "very-strong";
    readonly deprecated: boolean;
    readonly description: string;
}

/**
 * Type definitions for SecureString modular architecture
 */

/**
 * Configuration options for SecureString
 */
interface SecureStringOptions {
    /** Protection level for the underlying buffer */
    protectionLevel?: "basic" | "enhanced" | "maximum";
    /** Enable encryption for the buffer */
    enableEncryption?: boolean;
    /** Enable fragmentation for the buffer */
    enableFragmentation?: boolean;
    /** Enable canaries for the buffer */
    enableCanaries?: boolean;
    /** Enable obfuscation for the buffer */
    enableObfuscation?: boolean;
    /** Auto-lock the buffer */
    autoLock?: boolean;
    /** Use quantum-safe protection */
    quantumSafe?: boolean;
    /** Text encoding to use */
    encoding?: string;
    /** Enable advanced memory tracking */
    enableMemoryTracking?: boolean;
}
/**
 * String comparison result
 */
interface ComparisonResult {
    isEqual: boolean;
    timeTaken?: number;
    constantTime: boolean;
}
/**
 * String search options
 */
interface SearchOptions {
    caseSensitive?: boolean;
    wholeWord?: boolean;
    startPosition?: number;
    endPosition?: number;
}
/**
 * String split options
 */
interface SplitOptions {
    limit?: number;
    removeEmpty?: boolean;
    trim?: boolean;
}
/**
 * String validation result
 */
interface ValidationResult {
    isValid: boolean;
    errors: string[];
    warnings: string[];
    score?: number;
}
/**
 * String statistics
 */
interface StringStatistics {
    length: number;
    byteLength: number;
    characterCount: Record<string, number>;
    hasUpperCase: boolean;
    hasLowerCase: boolean;
    hasNumbers: boolean;
    hasSpecialChars: boolean;
    entropy: number;
}
/**
 * Event types for SecureString operations
 */
type SecureStringEvent = "created" | "modified" | "accessed" | "hashed" | "compared" | "destroyed";
/**
 * Event listener callback for SecureString
 */
type SecureStringEventListener = (event: SecureStringEvent, details?: any) => void;
/**
 * Memory usage information
 */
interface MemoryUsage {
    bufferSize: number;
    actualLength: number;
    overhead: number;
    isFragmented: boolean;
    isEncrypted: boolean;
}

/**
 * Advanced entropy analysis results
 */
interface EntropyAnalysisResult {
    shannonEntropy: number;
    minEntropy: number;
    maxEntropy: number;
    diversityScore: number;
    patternComplexity: number;
    characterDistribution: Record<string, number>;
    bigramEntropy: number;
    trigramEntropy: number;
    predictability: number;
    randomnessScore: number;
    recommendations: string[];
}
/**
 * Pattern analysis results
 */
interface PatternAnalysisResult {
    repeatingPatterns: Array<{
        pattern: string;
        count: number;
        positions: number[];
    }>;
    sequentialPatterns: Array<{
        pattern: string;
        type: "ascending" | "descending";
    }>;
    keyboardPatterns: Array<{
        pattern: string;
        layout: string;
    }>;
    dictionaryWords: Array<{
        word: string;
        position: number;
        confidence: number;
    }>;
    commonSubstitutions: Array<{
        original: string;
        substituted: string;
    }>;
    overallComplexity: number;
}

/**
 * String Validator Module
 * Handles validation and analysis of string content
 */

/**
 * Handles string validation and analysis
 */
declare class StringValidator {
    /**
     * Validates if a string meets password requirements
     */
    static validatePassword(password: string, requirements?: {
        minLength?: number;
        maxLength?: number;
        requireUppercase?: boolean;
        requireLowercase?: boolean;
        requireNumbers?: boolean;
        requireSpecialChars?: boolean;
        forbiddenPatterns?: RegExp[];
        customRules?: Array<(password: string) => string | null>;
    }): ValidationResult;
    /**
     * Validates email format
     */
    static validateEmail(email: string): ValidationResult;
    /**
     * Validates URL format
     */
    static validateURL(url: string): ValidationResult;
    /**
     * Validates phone number format
     */
    static validatePhoneNumber(phone: string, format?: 'international' | 'us' | 'flexible'): ValidationResult;
    /**
     * Validates credit card number using Luhn algorithm
     */
    static validateCreditCard(cardNumber: string): ValidationResult;
    /**
     * Calculates password strength score (0-100)
     */
    static calculatePasswordStrength(password: string): number;
    /**
     * Calculates Shannon entropy of a string
     */
    static calculateEntropy(str: string): number;
    /**
     * Gets detailed string statistics
     */
    static getStringStatistics(str: string): StringStatistics;
    /**
     * Checks if string contains only printable ASCII characters
     */
    static isPrintableASCII(str: string): boolean;
    /**
     * Checks if string is valid UTF-8
     */
    static isValidUTF8(str: string): boolean;
    /**
     * Validates JSON string
     */
    static validateJSON(str: string): ValidationResult;
    /**
     * Validates XML string (basic check)
     */
    static validateXML(str: string): ValidationResult;
}

/**
 * Quantum-Safe Operations Module
 * Provides quantum-resistant cryptographic operations for SecureString
 * Optimized for real-world applications with actual cryptographic implementations
 */

/**
 * Quantum-safe algorithm options
 */
interface QuantumSafeOptions {
    algorithm: "CRYSTALS-Dilithium" | "FALCON" | "SPHINCS+" | "Post-Quantum-Hash";
    securityLevel: 128 | 192 | 256;
    useHybridMode?: boolean;
    classicalFallback?: HashAlgorithm$1;
}
/**
 * Quantum-safe hash result
 */
interface QuantumSafeHashResult {
    hash: string | Uint8Array;
    algorithm: string;
    securityLevel: number;
    isQuantumSafe: boolean;
    hybridMode: boolean;
    metadata: {
        timestamp: Date;
        rounds: number;
        saltLength: number;
        keyLength: number;
    };
}
/**
 * Quantum-safe key derivation result
 */
interface QuantumSafeKeyResult {
    derivedKey: string | Uint8Array;
    salt: string | Uint8Array;
    algorithm: string;
    iterations: number;
    securityLevel: number;
    isQuantumSafe: boolean;
    metadata: {
        timestamp: Date;
        memoryUsage: number;
        computationTime: number;
    };
}

/**
 * Performance statistics
 */
interface PerformanceStats {
    totalOperations: number;
    averageDuration: number;
    minDuration: number;
    maxDuration: number;
    totalMemoryUsed: number;
    averageMemoryUsage: number;
    operationBreakdown: Record<string, number>;
    throughputStats: {
        average: number;
        peak: number;
        current: number;
    };
    recommendations: string[];
}
/**
 * Performance benchmark result
 */
interface BenchmarkResult {
    operation: string;
    iterations: number;
    totalTime: number;
    averageTime: number;
    operationsPerSecond: number;
    memoryEfficiency: number;
    scalabilityScore: number;
    recommendations: string[];
}

/**
 * A secure string that can be explicitly cleared from memory with modular architecture
 */
declare class SecureString {
    private bufferManager;
    private eventListeners;
    private _isDestroyed;
    private readonly _id;
    private _memoryTracking;
    private _createdAt;
    private secureStringPool?;
    /**
     * Creates a new secure string with enhanced memory management
     */
    constructor(value?: string, options?: SecureStringOptions);
    /**
     * Creates a SecureString from another SecureString (copy constructor)
     */
    static from(other: SecureString): SecureString;
    /**
     * Creates a SecureString from a buffer
     */
    static fromBuffer(buffer: Uint8Array, options?: SecureStringOptions, encoding?: string): SecureString;
    /**
     * Gets the string value
     */
    toString(): string;
    /**
     * Gets the raw buffer (copy)
     */
    toBuffer(): Uint8Array;
    /**
     * Gets the length of the string
     */
    length(): number;
    /**
     * Gets the byte length of the string in UTF-8 encoding
     */
    byteLength(): number;
    /**
     * Checks if the string is empty
     */
    isEmpty(): boolean;
    /**
     * Checks if the SecureString has been destroyed
     */
    isDestroyed(): boolean;
    /**
     * Appends another string
     */
    append(value: string | SecureString): SecureString;
    /**
     * Prepends another string
     */
    prepend(value: string | SecureString): SecureString;
    /**
     * Replaces the entire content with a new value
     */
    replace(value: string | SecureString): SecureString;
    /**
     * Extracts a substring
     */
    substring(start: number, end?: number): SecureString;
    /**
     * Splits the string into an array of SecureStrings
     */
    split(separator: string | RegExp, options?: SplitOptions): SecureString[];
    /**
     * Trims whitespace from both ends
     */
    trim(): SecureString;
    /**
     * Converts to uppercase
     */
    toUpperCase(): SecureString;
    /**
     * Converts to lowercase
     */
    toLowerCase(): SecureString;
    /**
     * Compares this SecureString with another string (constant-time comparison)
     */
    equals(other: string | SecureString, constantTime?: boolean): boolean;
    /**
     * Performs detailed comparison with timing information
     */
    compare(other: string | SecureString, constantTime?: boolean): ComparisonResult;
    /**
     * Checks if the string contains a substring
     */
    includes(searchString: string | SecureString, options?: SearchOptions): boolean;
    /**
     * Checks if the string starts with a prefix
     */
    startsWith(searchString: string | SecureString, options?: SearchOptions): boolean;
    /**
     * Checks if the string ends with a suffix
     */
    endsWith(searchString: string | SecureString, options?: SearchOptions): boolean;
    /**
     * Validates the string as a password
     */
    validatePassword(requirements?: Parameters<typeof StringValidator.validatePassword>[1]): ValidationResult;
    /**
     * Validates the string as an email
     */
    validateEmail(): ValidationResult;
    /**
     * Gets detailed string statistics
     */
    getStatistics(): StringStatistics;
    /**
     * Ensures the SecureString hasn't been destroyed
     */
    private ensureNotDestroyed;
    /**
     * Emits an event to all registered listeners
     */
    private emit;
    /**
     * Creates a hash of the string content
     */
    hash(algorithm?: HashAlgorithm$1, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Creates an HMAC of the string content
     */
    hmac(options: HMACOptions, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Derives a key using PBKDF2
     */
    deriveKeyPBKDF2(options: PBKDF2Options, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Performs comprehensive entropy analysis
     */
    analyzeEntropy(): EntropyAnalysisResult;
    /**
     * Analyzes patterns in the string
     */
    analyzePatterns(): PatternAnalysisResult;
    /**
     * Creates a quantum-safe hash
     */
    createQuantumSafeHash(options: QuantumSafeOptions, format?: HashOutputFormat): Promise<QuantumSafeHashResult>;
    /**
     * Derives a quantum-safe key
     */
    deriveQuantumSafeKey(options: QuantumSafeOptions, keyLength?: number, format?: HashOutputFormat): Promise<QuantumSafeKeyResult>;
    /**
     * Verifies a quantum-safe hash
     */
    verifyQuantumSafeHash(expectedHash: string | Uint8Array, options: QuantumSafeOptions, format?: HashOutputFormat): Promise<boolean>;
    /**
     * Starts performance monitoring for this SecureString
     */
    startPerformanceMonitoring(): void;
    /**
     * Stops performance monitoring
     */
    stopPerformanceMonitoring(): void;
    /**
     * Gets performance statistics
     */
    getPerformanceStats(): PerformanceStats;
    /**
     * Benchmarks a specific operation on this SecureString
     */
    benchmarkOperation(operation: () => Promise<any> | any, operationName: string, iterations?: number): Promise<BenchmarkResult>;
    /**
     * Measures an operation with automatic performance recording
     */
    measureOperation<T>(operation: () => Promise<T> | T, operationType: string): Promise<T>;
    /**
     * Adds an event listener
     */
    addEventListener(event: SecureStringEvent, listener: SecureStringEventListener): void;
    /**
     * Removes an event listener
     */
    removeEventListener(event: SecureStringEvent, listener: SecureStringEventListener): void;
    /**
     * Removes all event listeners
     */
    removeAllEventListeners(event?: SecureStringEvent): void;
    /**
     * Gets memory usage information
     */
    getMemoryUsage(): MemoryUsage;
    /**
     * Gets the current options
     */
    getOptions(): Required<SecureStringOptions>;
    /**
     * Updates the options (may recreate buffer)
     */
    updateOptions(newOptions: Partial<SecureStringOptions>): void;
    /**
     * Creates a shallow copy of the SecureString
     */
    clone(): SecureString;
    /**
     * Executes a function with the string value and optionally clears it afterward
     */
    use<T>(fn: (value: string) => T, autoClear?: boolean): T;
    /**
     * Initialize secure string pool for efficient memory reuse
     */
    private initializeSecureStringPool;
    /**
     * Handle memory pressure situations
     */
    private handleMemoryPressure;
    /**
     * Secure wipe of buffer memory
     */
    private secureWipe;
    /**
     * Get enhanced memory usage statistics
     */
    getEnhancedMemoryUsage(): {
        bufferSize: number;
        actualLength: number;
        overhead: number;
        isFragmented: boolean;
        isEncrypted: boolean;
        formattedSize: string;
        age: number;
        poolStats?: any;
    };
    /**
     * Force garbage collection for this SecureString
     */
    forceGarbageCollection(): void;
    /**
     * Enable memory tracking for this SecureString
     */
    enableMemoryTracking(): this;
    /**
     * Disable memory tracking for this SecureString
     */
    disableMemoryTracking(): this;
    /**
     * Clears the string by zeroing its contents and marks as destroyed
     */
    clear(): void;
    /**
     * Alias for clear() - destroys the SecureString
     */
    destroy(): void;
    /**
     * Securely wipes the content without destroying the SecureString
     */
    wipe(): void;
    /**
     * Creates a JSON representation (warning: exposes the value)
     */
    toJSON(): {
        value: string;
        length: number;
        byteLength: number;
    };
    /**
     * Gets information about available algorithms
     */
    static getAlgorithmInfo(): Record<CryptoAlgorithm, AlgorithmInfo>;
    /**
     * Lists all supported hash algorithms
     */
    static getSupportedHashAlgorithms(): HashAlgorithm$1[];
    /**
     * Lists all supported HMAC algorithms
     */
    static getSupportedHMACAlgorithms(): HMACAlgorithm[];
    /**
     * Generates a cryptographically secure salt
     */
    static generateSalt(length?: number, format?: HashOutputFormat): string | Uint8Array<ArrayBufferLike>;
    /**
     * Performs constant-time hash comparison
     */
    static constantTimeHashCompare(hash1: string, hash2: string): boolean;
}

/**
 * Factory functions for common use cases
 */
/**
 * Creates a new SecureString with default settings
 */
declare function createSecureString(...args: ConstructorParameters<typeof SecureString>): SecureString;

/***************************************************************************
 * XyPrissSecurity - Secure Array Types
 *
 * This file contains type definitions for the SecureArray modular architecture
 *
 * @author Nehonix
 *
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */
/**
 * Type definitions for SecureObject modular architecture
 */

/**
 * Types that can be stored securely
 */
type SecureValue = string | number | boolean | Uint8Array | SecureString | any | null | undefined;
/**
 * Serialization options for SecureObject
 */
interface SerializationOptions$1 {
    includeMetadata?: boolean;
    encryptSensitive?: boolean;
    format?: "json" | "binary";
}
/**
 * Metadata for tracking secure values
 */
interface ValueMetadata {
    type: string;
    isSecure: boolean;
    created: Date;
    lastAccessed: Date;
    accessCount: number;
}
/**
 * Event types for SecureObject
 */
type SecureObjectEvent = "set" | "get" | "delete" | "clear" | "destroy" | "filtered" | "gc";
/**
 * Event listener callback
 */
type EventListener = (event: SecureObjectEvent, key?: string, value?: any) => void | Promise<void>;
/**
 * Configuration options for SecureObject
 */
interface SecureObjectOptions {
    readOnly?: boolean;
    autoDestroy?: boolean;
    encryptionKey?: string;
    maxMemory?: number;
    gcThreshold?: number;
    enableMemoryTracking?: boolean;
    autoCleanup?: boolean;
}
/**
 * Internal data structure for storing values
 */
interface SecureObjectData {
    data: Map<string, any>;
    secureBuffers: Map<string, any>;
    metadata: Map<string, ValueMetadata>;
}

/***************************************************************************
 * XyPrissSecurity - Secure Array Types
 *
 * This file contains type definitions for the SecureArray modular architecture
 *
 * @author Nehonix
 *
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */
/**
 * @license MIT
 * @see https://lab.nehonix.space
 * @description SecureObject Core Module
 *
 * Main SecureObject class
 */

/**
 * A secure object that can store sensitive data
 * T represents the initial type, but the object can be extended with additional keys
 */
declare class SecureObject<T extends Record<string, SecureValue> = Record<string, SecureValue>> {
    private data;
    private secureBuffers;
    private sensitiveKeysManager;
    private cryptoHandler;
    private metadataManager;
    private eventManager;
    private serializationHandler;
    private _isDestroyed;
    private _isReadOnly;
    private readonly _id;
    private _memoryTracking;
    private _autoCleanup;
    private _createdAt;
    private _lastAccessed;
    private secureBufferPool?;
    /**
     * Creates a new secure object
     */
    constructor(initialData?: Partial<T>, options?: SecureObjectOptions);
    /**
     * Creates a SecureObject from another SecureObject (deep copy)
     */
    static from<T extends Record<string, SecureValue>>(other: SecureObject<T>): SecureObject<T>;
    /**
     * Creates a read-only SecureObject
     */
    static readOnly<T extends Record<string, SecureValue>>(data: Partial<T>): SecureObject<T>;
    /**
     * Creates a read-only SecureObject (public usage)
     */
    /** Permanently enable read-only mode (cannot be disabled). */
    enableReadOnly(): this;
    /**
     * Gets the unique ID of this SecureObject
     */
    get id(): string;
    /**
     * Checks if the SecureObject is read-only
     */
    get isReadOnly(): boolean;
    /**
     * Checks if the SecureObject has been destroyed
     */
    get isDestroyed(): boolean;
    /**
     * Gets the number of stored values
     */
    get size(): number;
    /**
     * Checks if the object is empty
     */
    get isEmpty(): boolean;
    /**
     * Ensures the SecureObject hasn't been destroyed
     */
    private ensureNotDestroyed;
    /**
     * Ensures the SecureObject is not read-only for write operations
     */
    private ensureNotReadOnly;
    /**
     * Updates the last accessed timestamp for memory management
     */
    private updateLastAccessed;
    /**
     * Initialize secure buffer pool for efficient memory reuse
     */
    private initializeSecureBufferPool;
    /**
     * Handle memory pressure situations
     */
    private handleMemoryPressure;
    /**
     * Secure wipe of buffer memory
     */
    private secureWipe;
    /**
     * Gets enhanced memory usage statistics for this SecureObject
     */
    getMemoryUsage(): {
        allocatedMemory: number;
        bufferCount: number;
        dataSize: number;
        createdAt: number;
        lastAccessed: number;
        age: number;
        formattedMemory: string;
        poolStats?: any;
    };
    /**
     * Forces enhanced garbage collection for this SecureObject
     */
    forceGarbageCollection(): void;
    /**
     * Enables memory tracking for this SecureObject
     */
    enableMemoryTracking(): this;
    /**
     * Disables memory tracking for this SecureObject
     */
    disableMemoryTracking(): this;
    /**
     * Adds keys to the sensitive keys list
     */
    addSensitiveKeys(...keys: string[]): this;
    /**
     * Removes keys from the sensitive keys list
     */
    removeSensitiveKeys(...keys: string[]): this;
    /**
     * Sets the complete list of sensitive keys (replaces existing list)
     */
    setSensitiveKeys(keys: string[]): this;
    /**
     * Gets the current list of sensitive keys
     */
    getSensitiveKeys(): string[];
    /**
     * Checks if a key is marked as sensitive
     */
    isSensitiveKey(key: string): boolean;
    /**
     * Clears all sensitive keys
     */
    clearSensitiveKeys(): this;
    /**
     * Resets sensitive keys to default values
     */
    resetToDefaultSensitiveKeys(): this;
    /**
     * Gets the default sensitive keys that are automatically initialized
     */
    static get getDefaultSensitiveKeys(): string[];
    /**
     * Adds custom regex patterns for sensitive key detection
     * @param patterns - Regex patterns or strings to match sensitive keys
     */
    addSensitivePatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Removes custom sensitive patterns
     */
    removeSensitivePatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Clears all custom sensitive patterns
     */
    clearSensitivePatterns(): this;
    /**
     * Gets all custom sensitive patterns
     */
    getSensitivePatterns(): RegExp[];
    /**
     * Sets the encryption key for sensitive data encryption
     */
    setEncryptionKey(key?: string | null): this;
    /**
     * Gets the current encryption key
     */
    get getEncryptionKey(): string | null;
    /**
     * Decrypts a value using the encryption key
     */
    decryptValue(encryptedValue: string): any;
    /**
     * Decrypts all encrypted values in an object
     */
    decryptObject(obj: any): any;
    /**
     * Encrypts all values in the object using AES-256-CTR-HMAC encryption
     * with proper memory management and atomic operations
     */
    encryptAll(): this;
    /**
     * Gets the raw encrypted data without decryption (for verification)
     */
    getRawEncryptedData(): Map<string, any>;
    /**
     * Gets a specific key's raw encrypted form (for verification)
     */
    getRawEncryptedValue(key: string): any;
    /**
     * Gets encryption status from the crypto handler
     */
    getEncryptionStatus(): {
        isInitialized: boolean;
        hasEncryptionKey: boolean;
        algorithm: string;
    };
    /**
     * Adds an event listener
     */
    addEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Removes an event listener
     */
    removeEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Creates a one-time event listener
     */
    once(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Waits for a specific event to be emitted
     */
    waitFor(event: SecureObjectEvent, timeout?: number): Promise<{
        key?: string;
        value?: any;
    }>;
    /**
     * Sets a value - allows both existing keys and new dynamic keys
     */
    set<K extends string>(key: K, value: SecureValue): this;
    /**
     * Sets multiple values at once
     */
    setAll(values: Partial<T>): this;
    /**
     * Gets a value with automatic decryption
     */
    get<K extends keyof T>(key: K): T[K];
    /**
     * Gets a value safely, returning undefined if key doesn't exist
     */
    getSafe<K extends keyof T>(key: K): T[K] | undefined;
    /**
     * Gets a value with a default fallback
     */
    getWithDefault<K extends keyof T>(key: K, defaultValue: T[K]): T[K];
    /**
     * Checks if a key exists
     */
    has<K extends keyof T>(key: K): boolean;
    /**
     * Deletes a key - allows both existing keys and dynamic keys
     */
    delete<K extends string>(key: K): boolean;
    /**
     * Cleans up resources associated with a key
     */
    private cleanupKey;
    /**
     * Clears all data
     */
    clear(): void;
    /**
     * Gets all keys
     */
    keys(): Array<keyof T>;
    /**
     * Gets all values
     */
    values(): Array<T[keyof T]>;
    /**
     * Gets all entries as [key, value] pairs
     */
    entries(): Array<[keyof T, T[keyof T]]>;
    /**
     * Iterates over each key-value pair
     */
    forEach(callback: (value: T[keyof T], key: keyof T, obj: this) => void): void;
    /**
     * Maps over values and returns a new array
     */
    map<U>(callback: (value: T[keyof T], key: keyof T, obj: this) => U): U[];
    /**
     * Filters entries based on a predicate function (like Array.filter)
     * Returns a new SecureObject with only the entries that match the condition
     */
    filter(predicate: (value: T[keyof T], key: keyof T, obj: this) => boolean): SecureObject<Partial<T>>;
    /**
     * Filters entries by specific key names (type-safe for known keys)
     * Returns a new SecureObject with only the specified keys
     *
     * @example
     * const user = createSecureObject({ name: "John", password: "secret", age: 30 });
     * const credentials = user.filterByKeys("name", "password");
     */
    filterByKeys<K extends keyof T>(...keys: K[]): SecureObject<Pick<T, K>>;
    /**
     * Filters entries by value type using a type guard function
     * Returns a new SecureObject with only values of the specified type
     *
     * @example
     * const data = createSecureObject({ name: "John", age: 30, active: true });
     * const strings = data.filterByType((v): v is string => typeof v === "string");
     */
    filterByType<U>(typeGuard: (value: any) => value is U): SecureObject<Record<string, U>>;
    /**
     * Filters entries to only include sensitive keys
     * Returns a new SecureObject with only sensitive data
     *
     * @example
     * const user = createSecureObject({ name: "John", password: "secret", age: 30 });
     * user.addSensitiveKeys("password");
     * const sensitiveData = user.filterSensitive(); // Only contains password
     */
    filterSensitive(): SecureObject<Partial<T>>;
    /**
     * Filters entries to exclude sensitive keys
     * Returns a new SecureObject with only non-sensitive data
     *
     * @example
     * const user = createSecureObject({ name: "John", password: "secret", age: 30 });
     * user.addSensitiveKeys("password");
     * const publicData = user.filterNonSensitive(); // Contains name and age
     */
    filterNonSensitive(options?: {
        strictMode?: boolean;
    }): SecureObject<Partial<T>>;
    /**
     * Processes nested objects for filtering with the same strict mode
     */
    private processNestedObjectForFiltering;
    /**
     * Gets metadata for a specific key
     */
    getMetadata<K extends keyof T>(key: K): ValueMetadata | undefined;
    /**
     * Gets metadata for all keys
     */
    getAllMetadata(): Map<string, ValueMetadata>;
    /**
     * Converts to a regular object with security-focused serialization
     *
     * BEHAVIOR: This is the security-focused method that handles sensitive key filtering.
     * Use this method when you need controlled access to data with security considerations.
     * For simple object conversion without filtering, use toObject().
     *
     *  @example
     * const user = fObject({
        id: "1",
        email: "test@test.com",
        password: "test123",
        isVerified: true,
        userName: "test",
        firstName: "test",
        lastName: "test",
        bio: "test",
        });

        const getAllResult = user.getAll();
        console.log("getAllResult.email:", getAllResult.email);
        console.log("getAllResult.password:", getAllResult.password);
        console.log("Has password?", "password" in getAllResult);
        
        // Purpose: Security-conscious data access
        // Behavior: Filters out sensitive keys by default
        // Result:  password: undefined (filtered for security)
        // With encryptSensitive: true: ✔ password: "[ENCRYPTED:...]" (encrypted but included)
     */
    getAll(options?: SerializationOptions$1): T & {
        _metadata?: Record<string, ValueMetadata>;
    };
    /**
     * Gets the full object as a regular JavaScript object
     *
     * BEHAVIOR: Returns ALL data including sensitive keys (like standard JS object conversion).
     * This method does NOT filter sensitive keys by default - use getAll() for security-focused serialization.
     *
     * @example
     * const user = fObject({
        id: "1",
        email: "test@test.com",
        password: "test123",
        isVerified: true,
        userName: "test",
        firstName: "test",
        lastName: "test",
        bio: "test",
        });

        const toObjectResult = user.toObject();
        console.log("toObjectResult.email:", toObjectResult.email);
        console.log("toObjectResult.password:", toObjectResult.password);
        console.log("Has password?", "password" in toObjectResult);

        // Purpose: Standard JavaScript object conversion
        // Behavior: Returns ALL data including sensitive keys (like password)
        // Result: ✔ password: "test123" (included)

        Sensitive keys can be handled using .add/removeSensitiveKeys()
     */
    toObject(options?: SerializationOptions$1): T & {
        _metadata?: Record<string, ValueMetadata>;
    };
    /**
     * Converts to JSON string
     */
    toJSON(options?: SerializationOptions$1 & {
        strictSensitiveKeys?: boolean;
    }): string;
    /**
     * Creates a hash of the entire object content
     */
    hash(algorithm?: HashAlgorithm$1, format?: HashOutputFormat): Promise<string | Uint8Array>;
    /**
     * Executes a function with the object data and optionally clears it afterward
     */
    use<U>(fn: (obj: this) => U, autoClear?: boolean): U;
    /**
     * Creates a shallow copy of the SecureObject
     */
    clone(): SecureObject<T>;
    /**
     * Merges another object into this one
     */
    merge(other: Partial<T> | SecureObject<Partial<T>>, overwrite?: boolean): this;
    /**
     * Transform values with a mapper function (like Array.map but returns SecureObject)
     * Returns a new SecureObject with transformed values
     */
    transform<U>(mapper: (value: T[keyof T], key: keyof T, obj: this) => U): SecureObject<Record<string, U>>;
    /**
     * Group entries by a classifier function
     * Returns a Map where keys are group identifiers and values are SecureObjects
     */
    groupBy<K extends string | number>(classifier: (value: T[keyof T], key: keyof T) => K): Map<K, SecureObject<Partial<T>>>;
    /**
     * Partition entries into two groups based on a predicate
     * Returns [matching, notMatching] SecureObjects
     */
    partition(predicate: (value: T[keyof T], key: keyof T) => boolean): [SecureObject<Partial<T>>, SecureObject<Partial<T>>];
    /**
     * Pick specific keys (like Lodash pick but type-safe)
     * Returns a new SecureObject with only the specified keys
     */
    pick<K extends keyof T>(...keys: K[]): SecureObject<Pick<T, K>>;
    /**
     * Omit specific keys (opposite of pick)
     * Returns a new SecureObject without the specified keys
     */
    omit<K extends keyof T>(...keys: K[]): SecureObject<Omit<T, K>>;
    /**
     * Flatten nested objects (one level deep)
     * Converts { user: { name: "John" } } to { "user.name": "John" }
     */
    flatten(separator?: string): SecureObject<Record<string, any>>;
    /**
     * Compact - removes null, undefined, and empty values
     * Returns a new SecureObject with only truthy values
     */
    compact(): SecureObject<Partial<T>>;
    /**
     * Invert - swap keys and values
     * Returns a new SecureObject with keys and values swapped
     */
    invert(): SecureObject<Record<string, string>>;
    /**
     * Defaults - merge with default values (only for missing keys)
     * Returns a new SecureObject with defaults applied
     */
    defaults(defaultValues: Partial<T>): SecureObject<T>;
    /**
     * Tap - execute a function with the object and return the object (for chaining)
     * Useful for debugging or side effects in method chains
     */
    tap(fn: (obj: this) => void): this;
    /**
     * Pipe - transform the object through a series of functions
     * Each function receives the result of the previous function
     */
    pipe<U>(fn: (obj: this) => U): U;
    pipe<U, V>(fn1: (obj: this) => U, fn2: (obj: U) => V): V;
    pipe<U, V, W>(fn1: (obj: this) => U, fn2: (obj: U) => V, fn3: (obj: V) => W): W;
    /**
     * Sample - get random entries from the object
     * Returns a new SecureObject with randomly selected entries
     */
    sample(count?: number): SecureObject<Partial<T>>;
    /**
     * Shuffle - return a new SecureObject with keys in random order
     * Returns a new SecureObject with the same data but shuffled key order
     */
    shuffle(): SecureObject<T>;
    /**
     * Chunk - split object into chunks of specified size
     * Returns an array of SecureObjects, each containing up to 'size' entries
     */
    chunk(size: number): SecureObject<Partial<T>>[];
    /**
     * Serializes the SecureObject to a secure format
     */
    serialize(options?: SerializationOptions$1): string;
    /**
     * Exports the SecureObject data in various formats
     */
    exportData(format?: "json" | "csv" | "xml" | "yaml"): string;
    /**
     * Gets serialization metadata
     */
    private getSerializationMetadata;
    /**
     * Exports to CSV format
     */
    private exportToCSV;
    /**
     * Exports to XML format
     */
    private exportToXML;
    /**
     * Exports to YAML format
     */
    private exportToYAML;
    /**
     * Escapes XML special characters
     */
    private escapeXML;
    /**
     * Destroys the SecureObject and clears all data
     */
    destroy(): void;
}

/**
 * Sensitive Keys Management Module
 * Handles the management of sensitive keys for encryption/masking
 */
/**
 * Default sensitive keys that are commonly used in applications
 */
declare const DEFAULT_SENSITIVE_KEYS: readonly ["password", "passwd", "pwd", "secret", "token", "key", "apikey", "api_key", "accesskey", "access_key", "accesstoken", "access_token", "refreshtoken", "refresh_token", "sessionid", "session_id", "auth", "authorization", "bearer", "credential", "credentials", "pin", "ssn", "social_security", "credit_card", "creditcard", "cvv", "cvc", "private_key", "privatekey", "signature", "hash", "salt", "nonce", "otp", "passcode", "passphrase", "masterkey", "master_key", "encryption_key", "decryption_key", "jwt", "cookie", "session", "csrf", "xsrf"];
/**
 * Manages sensitive keys for a SecureObject instance
 */
declare class SensitiveKeysManager {
    private sensitiveKeys;
    private customPatterns;
    constructor(initialKeys?: string[]);
    /**
     * Adds keys to the sensitive keys list
     */
    add(...keys: string[]): this;
    /**
     * Removes keys from the sensitive keys list
     */
    remove(...keys: string[]): this;
    /**
     * Sets the complete list of sensitive keys (replaces existing)
     */
    set(keys: string[]): this;
    /**
     * Gets the current list of sensitive keys
     */
    getAll(): string[];
    /**
     * Adds custom regex patterns for sensitive key detection
     */
    addCustomPatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Removes custom patterns
     */
    removeCustomPatterns(...patterns: (RegExp | string)[]): this;
    /**
     * Clears all custom patterns
     */
    clearCustomPatterns(): this;
    /**
     * Gets all custom patterns
     */
    getCustomPatterns(): RegExp[];
    /**
     * Checks if a key is marked as sensitive
     * Simple approach: exact matches + custom patterns + strict mode patterns
     */
    isSensitive(key: string, strictMode?: boolean): boolean;
    /**
     * Simple strict mode pattern matching
     * Only applies additional patterns when in strict mode
     */
    private isStrictModePattern;
    /**
     * Clears all sensitive keys
     */
    clear(): this;
    /**
     * Resets to default sensitive keys
     */
    resetToDefault(): this;
    /**
     * Gets the default sensitive keys
     */
    static getDefaultKeys(): string[];
}

/**
 * Cryptographic Handler Module
 * Handles encryption and decryption of sensitive data
 */

/**
 * Handles encryption and decryption operations for SecureObject
 */
declare class CryptoHandler {
    private objectId;
    private encryptionKey;
    private derivedKey;
    private isInitialized;
    constructor(objectId: string);
    /**
     * Initialize cryptographic components
     */
    private initializeCrypto;
    /**
     * Sets the encryption key for sensitive data encryption
     */
    setEncryptionKey(key?: string | null): this;
    /**
     * Gets the current encryption key
     */
    getEncryptionKey(): string | null;
    /**
     * Encrypts a value using real AES-256-CTR-HMAC encryption
     */
    encryptValue(value: any): string;
    /**
     * Decrypts a value using real AES-256-CTR-HMAC decryption
     */
    decryptValue(encryptedValue: string): any;
    /**
     * Decrypts all encrypted values in an object recursively
     */
    decryptObject(obj: any): any;
    /**
     * Recursively processes nested objects to check for sensitive keys
     */
    processNestedObject(obj: any, options: SerializationOptions$1, sensitiveKeys: Set<string> | ((key: string) => boolean)): any;
    /**
     * Checks if a value is encrypted
     */
    isEncrypted(value: any): boolean;
    /**
     * Performs the actual encryption using a secure stream cipher
     */
    private performEncryption;
    /**
     * Performs the actual decryption
     */
    private performDecryption;
    /**
     * Generates a secure keystream for encryption/decryption
     */
    private generateKeystream;
    /**
     * Generates HMAC for authentication
     */
    private generateHMAC;
    /**
     * Constant-time comparison to prevent timing attacks
     */
    private constantTimeEqual;
    /**
     * Gets the current encryption status
     */
    getEncryptionStatus(): {
        isInitialized: boolean;
        hasEncryptionKey: boolean;
        algorithm: string;
    };
    /**
     * Securely destroys the crypto handler
     */
    destroy(): void;
}

/**
 * Metadata Manager Module
 * Handles metadata tracking for SecureObject values
 */

/**
 * Manages metadata for SecureObject values
 */
declare class MetadataManager {
    private metadata;
    /**
     * Updates metadata for a key
     */
    update(key: string, type: string, isSecure: boolean, isAccess?: boolean): void;
    /**
     * Gets metadata for a specific key
     */
    get(key: string): ValueMetadata | undefined;
    /**
     * Gets all metadata
     */
    getAll(): Map<string, ValueMetadata>;
    /**
     * Checks if metadata exists for a key
     */
    has(key: string): boolean;
    /**
     * Deletes metadata for a key
     */
    delete(key: string): boolean;
    /**
     * Clears all metadata
     */
    clear(): void;
    /**
     * Gets the number of metadata entries
     */
    get size(): number;
    /**
     * Gets all keys that have metadata
     */
    keys(): string[];
    /**
     * Gets all metadata values
     */
    values(): ValueMetadata[];
    /**
     * Gets all metadata entries as [key, metadata] pairs
     */
    entries(): [string, ValueMetadata][];
    /**
     * Gets statistics about the metadata
     */
    getStats(): {
        totalEntries: number;
        secureEntries: number;
        totalAccesses: number;
        averageAccesses: number;
        oldestEntry: Date | null;
        newestEntry: Date | null;
    };
    /**
     * Filters metadata by criteria
     */
    filter(predicate: (key: string, metadata: ValueMetadata) => boolean): Map<string, ValueMetadata>;
    /**
     * Gets metadata for secure values only
     */
    getSecureMetadata(): Map<string, ValueMetadata>;
    /**
     * Gets metadata for non-secure values only
     */
    getNonSecureMetadata(): Map<string, ValueMetadata>;
    /**
     * Gets the most accessed keys
     */
    getMostAccessed(limit?: number): [string, ValueMetadata][];
    /**
     * Gets the least accessed keys
     */
    getLeastAccessed(limit?: number): [string, ValueMetadata][];
    /**
     * Converts metadata to a plain object for serialization
     */
    toObject(): Record<string, ValueMetadata>;
    /**
     * Creates a MetadataManager from a plain object
     */
    static fromObject(obj: Record<string, ValueMetadata>): MetadataManager;
}

/**
 * Event Manager Module
 * Handles event system for SecureObject
 */

/**
 * Manages events for SecureObject instances
 */
declare class EventManager {
    private eventListeners;
    /**
     * Adds an event listener
     */
    addEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Removes an event listener
     */
    removeEventListener(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Removes all listeners for a specific event
     */
    removeAllListeners(event?: SecureObjectEvent): void;
    /**
     * Emits an event to all registered listeners
     */
    emit(event: SecureObjectEvent, key?: string, value?: any): void;
    /**
     * Gets the number of listeners for an event
     */
    getListenerCount(event: SecureObjectEvent): number;
    /**
     * Gets all registered event types
     */
    getRegisteredEvents(): SecureObjectEvent[];
    /**
     * Gets total number of listeners across all events
     */
    getTotalListenerCount(): number;
    /**
     * Checks if there are any listeners for an event
     */
    hasListeners(event: SecureObjectEvent): boolean;
    /**
     * Checks if there are any listeners at all
     */
    hasAnyListeners(): boolean;
    /**
     * Gets a copy of all listeners for an event
     */
    getListeners(event: SecureObjectEvent): EventListener[];
    /**
     * Creates a one-time event listener that removes itself after first execution
     */
    once(event: SecureObjectEvent, listener: EventListener): void;
    /**
     * Creates a promise that resolves when a specific event is emitted
     */
    waitFor(event: SecureObjectEvent, timeout?: number): Promise<{
        key?: string;
        value?: any;
    }>;
    /**
     * Emits an event and waits for all listeners to complete (if they return promises)
     */
    emitAsync(event: SecureObjectEvent, key?: string, value?: any): Promise<void>;
    /**
     * Creates a filtered event listener that only triggers for specific keys
     */
    addKeyFilteredListener(event: SecureObjectEvent, keys: string[], listener: EventListener): void;
    /**
     * Clears all event listeners (used during destruction)
     */
    clear(): void;
    /**
     * Gets debug information about the event system
     */
    getDebugInfo(): {
        totalEvents: number;
        totalListeners: number;
        eventBreakdown: Record<SecureObjectEvent, number>;
    };
}

/**
 * Serialization Handler Module
 * Handles object serialization and format conversion
 */

/**
 * Handles serialization operations for SecureObject
 */
declare class SerializationHandler {
    private cryptoHandler;
    private metadataManager;
    constructor(cryptoHandler: CryptoHandler, metadataManager: MetadataManager);
    /**
     * Converts SecureObject data to a regular object
     */
    toObject<T>(data: Map<string, any>, sensitiveKeys: Set<string> | ((key: string) => boolean), options?: SerializationOptions$1): T & {
        _metadata?: Record<string, ValueMetadata>;
    };
    /**
     * Processes a single value for serialization
     */
    private processValue;
    /**
     * Applies format transformation to the result
     */
    private applyFormat;
    /**
     * Converts to JSON string
     */
    toJSON<T>(data: Map<string, any>, sensitiveKeys: Set<string> | ((key: string) => boolean), options?: SerializationOptions$1): string;
    /**
     * Creates a deterministic representation for hashing
     */
    createHashableRepresentation(entries: Array<[any, any]>): string;
    /**
     * Processes nested objects recursively for sensitive key detection
     */
    processNestedObject(obj: any, options: SerializationOptions$1, sensitiveKeys: Set<string> | ((key: string) => boolean)): any;
    /**
     * Validates serialization options
     */
    validateOptions(options: SerializationOptions$1): void;
    /**
     * Gets serialization statistics
     */
    getSerializationStats(data: Map<string, any>): {
        totalKeys: number;
        secureBufferCount: number;
        secureStringCount: number;
        nestedObjectCount: number;
        primitiveCount: number;
    };
    /**
     * Estimates serialized size
     */
    estimateSerializedSize(data: Map<string, any>, options?: SerializationOptions$1): number;
}

/**
 * ID Generator Utility
 * Generates unique IDs for SecureObject instances
 */
/**
 * Generates unique IDs for SecureObject instances
 */
declare class IdGenerator {
    /**
     * Generates a unique ID for a SecureObject instance
     */
    static generate(): string;
    /**
     * Generates a unique ID with custom prefix
     */
    static generateWithPrefix(prefix: string): string;
    /**
     * Generates a unique ID with custom size
     */
    static generateWithSize(size: number): string;
    /**
     * Generates a unique ID with custom prefix and size
     */
    static generateCustom(prefix: string, size: number): string;
    /**
     * Validates if a string looks like a valid SecureObject ID
     */
    static isValidId(id: string): boolean;
    /**
     * Extracts the prefix from an ID
     */
    static extractPrefix(id: string): string | null;
    /**
     * Extracts the unique part from an ID (without prefix)
     */
    static extractUniquePart(id: string): string | null;
}

/**
 * Validation Utilities
 * Common validation functions for SecureObject
 */

/**
 * Validation utilities for SecureObject
 */
declare class ValidationUtils {
    /**
     * Validates if a value is a valid SecureValue type
     */
    static isValidSecureValue(value: any): value is SecureValue;
    /**
     * Checks if a value is a SecureString instance
     */
    static isSecureString(value: any): boolean;
    /**
     * Checks if a value is a SecureObject instance
     */
    static isSecureObject(value: any): boolean;
    /**
     * Validates serialization options
     */
    static validateSerializationOptions(options: SerializationOptions$1): void;
    /**
     * Validates a key for SecureObject operations
     */
    static validateKey(key: any): void;
    /**
     * Validates an array of keys
     */
    static validateKeys(keys: any[]): void;
    /**
     * Validates an encryption key
     */
    static validateEncryptionKey(key: any): void;
    /**
     * Validates a timeout value
     */
    static validateTimeout(timeout: any): void;
    /**
     * Validates a limit value for pagination/filtering
     */
    static validateLimit(limit: any): void;
    /**
     * Validates a callback function
     */
    static validateCallback(callback: any, name?: string): void;
    /**
     * Validates an event listener
     */
    static validateEventListener(listener: any): void;
    /**
     * Validates an event type
     */
    static validateEventType(event: any): void;
    /**
     * Validates a predicate function
     */
    static validatePredicate(predicate: any): void;
    /**
     * Validates a mapping function
     */
    static validateMapper(mapper: any): void;
    /**
     * Sanitizes a key to ensure it's a string
     */
    static sanitizeKey(key: any): string;
    /**
     * Checks if an object is empty (null, undefined, or has no properties)
     */
    static isEmpty(obj: any): boolean;
    /**
     * Deep clones a value (for non-secure values only)
     */
    static deepClone<T>(value: T): T;
    /**
     * Checks if a value is a primitive type
     */
    static isPrimitive(value: any): boolean;
    /**
     * Gets the type name of a value
     */
    static getTypeName(value: any): string;
}

/***************************************************************************
 * XyPrissSecurity - Secure Array Types
 *
 * This file contains type definitions for the SecureArray modular architecture
 *
 * @author Nehonix
 *
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */
/**
 * Main export file for SecureObject
 */

/**
 * Factory functions for common use cases
 */
/**
 * Creates a new SecureObject with default settings
 */
declare function createSecureObject<T extends Record<string, any>>(...args: ConstructorParameters<typeof SecureObject<T>>): SecureObject<T>;
/**
 * Creates a read-only SecureObject
 */
declare function createReadOnlySecureObject<T extends Record<string, any>>(data: Partial<T>): SecureObject<T>;
/**
 * Creates a SecureObject with custom sensitive keys
 */
declare function createSecureObjectWithSensitiveKeys<T extends Record<string, any>>(initialData: Partial<T>, sensitiveKeys: string[], options?: {
    readOnly?: boolean;
    encryptionKey?: string;
}): SecureObject<T>;
/**
 * Creates a SecureObject from another SecureObject (deep copy)
 */
declare function cloneSecureObject<T extends Record<string, any>>(source: SecureObject<T>): SecureObject<T>;
/**
 * Version information
 */
declare const SECURE_OBJECT_VERSION = "2.0.0-modular";
/**
 * Module information for debugging
 */
declare const MODULE_INFO: {
    readonly version: "2.0.0-modular";
    readonly architecture: "modular";
    readonly components: readonly ["core/secure-object-core", "encryption/sensitive-keys", "encryption/crypto-handler", "metadata/metadata-manager", "events/event-manager", "serialization/serialization-handler", "utils/id-generator", "utils/validation"];
    readonly features: readonly ["Modular architecture", "Type-safe operations", "Event system", "Metadata tracking", "Encryption support", "Serialization options", "Memory management", "Validation utilities"];
};

/**
 * XyPrissJS Express Encryption Service
 *  encryption/decryption service using XyPrissJS cryptographic utilities
 *
 * Features:
 * - AES-256-GCM encryption with authentication
 * - ChaCha20-Poly1305 fallback for quantum-safe encryption
 * - Proper key derivation using PBKDF2
 * - Secure IV/nonce generation
 * - Constant-time operations
 * - Memory-safe operations with secure wiping
 */
/**
 * Encryption algorithm options
 */
type EncryptionAlgorithm = "aes-256-gcm" | "chacha20-poly1305";
/**
 * Encryption options
 */
interface EncryptionOptions {
    algorithm?: EncryptionAlgorithm;
    keyDerivationIterations?: number;
    additionalData?: string;
    quantumSafe?: boolean;
}
/**
 *  encryption service using XyPrissJS utilities
 */
declare class EncryptionService {
    private static readonly VERSION;
    private static readonly DEFAULT_ITERATIONS;
    private static readonly KEY_LENGTH;
    private static readonly IV_LENGTH;
    private static readonly SALT_LENGTH;
    private static readonly AUTH_TAG_LENGTH;
    /**
     * Encrypt data using production-grade encryption
     */
    static encrypt(data: any, key: string, options?: EncryptionOptions): Promise<string>;
    /**
     * Decrypt data using production-grade decryption
     */
    static decrypt(encryptedData: string, key: string): Promise<any>;
    /**
     * Derive encryption key using PBKDF2
     */
    private static deriveKey;
    /**
     * Generate secure IV/nonce for encryption
     */
    private static generateIV;
    /**
     * Encrypt using AES-256-GCM
     */
    private static encryptAES256GCM;
    /**
     * Decrypt using AES-256-GCM
     */
    private static decryptAES256GCM;
    /**
     * Encrypt using ChaCha20-Poly1305 (quantum-safe fallback)
     */
    private static encryptChaCha20Poly1305;
    /**
     * Decrypt using ChaCha20-Poly1305
     */
    private static decryptChaCha20Poly1305;
    /**
     * Validate inputs for encryption
     */
    private static validateInputs;
    /**
     * Validate encrypted package structure
     */
    private static validatePackage;
    /**
     * Convert buffer to hex string
     */
    private static bufferToHex;
    /**
     * Convert hex string to buffer
     */
    private static hexToBuffer;
    /**
     * Secure memory wipe using XyPrissJS utilities
     */
    private static secureWipe;
    /**
     * Generate a secure session key for temporary use
     */
    static generateSessionKey(): string;
    /**
     * Verify the integrity of encrypted data without decrypting
     */
    static verifyIntegrity(encryptedData: string): boolean;
    /**
     * Get encryption metadata without decrypting
     */
    static getMetadata(encryptedData: string): {
        algorithm: EncryptionAlgorithm;
        timestamp: number;
        version: string;
    };
}

/***************************************************************************
 * XyPrissSecurity - Secure Array Types
 *
 * This file contains type definitions for the SecureArray modular architecture
 *
 * @author Nehonix
 *
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */

/**
 * Main class for the XyPrissSecurity library
 */
declare class XyPrissSecurity {
    /**
     * Generate a secure token with customizable options
     * @param options - Token generation options
     * @returns Secure random token
     */
    static generateSecureToken(options?: SecureTokenOptions): string;
    /**
     * Generate secure PIN
     * @param length - PIN length
     * @param options - Generation options
     * @returns Secure numeric PIN
     */
    static generateSecurePIN(...args: Parameters<(typeof RandomTokens)["generateSecurePIN"]>): string;
    /**
     * Generate recovery codes
     * @param count - Number of codes to generate
     * @param codeLength - Length of each code
     * @param options - Generation options
     * @returns Array of recovery codes
     */
    static generateRecoveryCodes(...args: Parameters<(typeof RandomTokens)["generateRecoveryCodes"]>): string[];
    /**
     * Generate an API key with prefix and timestamp
     * @param options - API key generation options
     * @returns API key
     */
    static generateAPIKey(options?: APIKeyOptions | string): string;
    /**
     * Generate a JWT secret with high entropy
     * @param length - Length of the secret
     * @returns High-entropy JWT secret
     */
    static generateJWTSecret(length?: number, encoding?: EncodingHashType$1): string;
    /**
     * Generate a session token with built-in signature
     * @param options - Session token options
     * @returns Session token
     */
    static generateSessionToken(options?: SessionTokenOptions): string;
    /**
     * Generate a TOTP secret for two-factor authentication
     * @returns Base32 encoded TOTP secret
     */
    static generateTOTPSecret(): string;
    /**
     * Create a secure hash with configurable options
     * @param input - The input to hash
     * @param options - Hashing options
     * @returns The hash in the specified format
     */
    static secureHash(...p: Parameters<typeof Hash.createSecureHash>): string;
    /**
     * Verify that a hash matches the expected input
     * @param input - The input to verify
     * @param hash - The hash to verify against
     * @param options - Hashing options (must match those used to create the hash)
     * @returns True if the hash matches the input
     */
    static verifyHash(...p: Parameters<typeof Hash.verifyHash>): boolean;
    /**
     * Derive a key from a password or other input
     * @param input - The input to derive a key from
     * @param options - Key derivation options
     * @returns The derived key as a hex string
     */
    static deriveKey(input: string | Uint8Array, options?: KeyDerivationOptions): string;
    /**
     * Calculate password strength with detailed analysis
     * @param password - The password to analyze
     * @returns Password strength analysis
     */
    static calculatePasswordStrength(password: string): PasswordStrengthResult;
    /**
     * Run security tests to validate the library's functionality
     * @returns Security test results
     */
    /**
     * Get cryptographic operation statistics
     * @returns Current statistics
     */
    static getStats(): CryptoStats;
    /**
     * Reset statistics
     */
    static resetStats(): void;
    /**
     * Perform a constant-time comparison of two strings or arrays
     * This prevents timing attacks by ensuring the comparison takes the same
     * amount of time regardless of how many characters match
     *
     * @param a - First string or array to compare
     * @param b - Second string or array to compare
     * @returns True if the inputs are equal, false otherwise
     */
    static constantTimeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
    /**
     * Derive a key using memory-hard Argon2 algorithm
     * This is more resistant to hardware-based attacks than standard PBKDF2
     *
     * @param password - Password to derive key from
     * @param options - Derivation options
     * @returns Derived key and metadata
     */
    static deriveKeyMemoryHard(password: string | Uint8Array, options?: any): any;
    /**
     * Derive a key using memory-hard Balloon algorithm
     * An alternative memory-hard algorithm with different security properties
     *
     * @param password - Password to derive key from
     * @param options - Derivation options
     * @returns Derived key and metadata
     */
    static deriveKeyBalloon(password: string | Uint8Array, options?: any): any;
    /**
     * Generate a post-quantum secure key pair using Lamport one-time signatures
     * This is resistant to attacks by quantum computers
     *
     * @returns Public and private key pair
     */
    static generateQuantumResistantKeypair(): any;
    /**
     * Sign a message using quantum-resistant Lamport signatures
     *
     * @param message - Message to sign
     * @param privateKey - Private key
     * @returns Signature
     */
    static quantumResistantSign(message: string | Uint8Array, privateKey: string): string;
    /**
     * Verify a quantum-resistant signature
     *
     * @param message - Message that was signed
     * @param signature - Signature to verify
     * @param publicKey - Public key
     * @returns True if the signature is valid
     */
    static quantumResistantVerify(message: string | Uint8Array, signature: string, publicKey: string): boolean;
    /**
     * Create a secure buffer that automatically zeros its contents when destroyed
     *
     * @param size - Size of the buffer in bytes
     * @param fill - Optional value to fill the buffer with
     * @returns Secure buffer
     */
    static createSecureBuffer(size: number, fill?: number): SecureBuffer;
    /**
     * Create a secure string that can be explicitly cleared from memory
     *
     * @param value - Initial string value
     * @returns Secure string
     */
    static createSecureString(value?: string): SecureString;
    /**
     * Create a secure object that can store sensitive data and be explicitly cleared
     *
     * @param initialData - Initial data
     * @returns Secure object
     */
    static createSecureObject<T extends Record<string, any>>(initialData?: T): SecureObject<T>;
    /**
     * Securely wipe a section of memory
     *
     * @param buffer - Buffer to wipe
     * @param start - Start position
     * @param end - End position
     */
    static secureWipe(buffer: Uint8Array, start?: number, end?: number): void;
    /**
     * Get an enhanced entropy source that collects entropy from multiple sources
     *
     * @param poolSize - Size of the entropy pool in bytes
     * @param options - Entropy collection options
     * @returns Entropy pool instance
     */
    static getEnhancedEntropySource(poolSize?: number, options?: any): EntropyPool;
    /**
     * Create a canary token that can detect unauthorized access
     *
     * @param options - Canary options
     * @returns Canary token
     */
    static createCanaryToken(options?: any): string;
    /**
     * Create a canary object that triggers when accessed
     *
     * @param target - Object to wrap with a canary
     * @param options - Canary options
     * @returns Proxy object that triggers the canary when accessed
     */
    static createCanaryObject<T extends object>(target: T, options?: any): T;
    /**
     * Create a canary function that triggers when called
     *
     * @param fn - Function to wrap with a canary
     * @param options - Canary options
     * @returns Function that triggers the canary when called
     */
    static createCanaryFunction<T extends Function>(fn: T, options?: any): T;
    /**
     * Create a cryptographic attestation for data
     *
     * @param data - Data to attest
     * @param options - Attestation options
     * @returns Attestation string
     */
    static createAttestation(data: string | Uint8Array | Record<string, any>, options?: any): string;
    /**
     * Verify a cryptographic attestation
     *
     * @param attestation - Attestation to verify
     * @param options - Verification options
     * @returns Verification result
     */
    static verifyAttestation(attestation: string, options: any): any;
    /**
     * Create an attestation for the library itself
     *
     * @param options - Attestation options
     * @returns Attestation string
     */
    static createLibraryAttestation(options?: any): string;
    /**
     * Verify a library attestation
     *
     * @param attestation - Attestation to verify
     * @param options - Verification options
     * @returns Verification result
     */
    static verifyLibraryAttestation(attestation: string, options: any): any;
    /**
     * Verify the security of the runtime environment
     *
     * @param options - Verification options
     * @returns Verification result
     */
    static verifyRuntimeSecurity(options?: any): any;
    /**
     * Securely serialize data with protection against various attacks
     *
     * @param data - Data to serialize
     * @param options - Serialization options
     * @returns Serialization result
     */
    static secureSerialize<T>(data: T, options?: any): any;
    /**
     * Securely deserialize data
     *
     * @param serialized - Serialized data
     * @param options - Deserialization options
     * @returns Deserialization result
     */
    static secureDeserialize<T>(serialized: any, options?: any): any;
    /**
     * Create a tamper-evident logger
     *
     * @param key - Secret key for hashing
     * @param storageKey - Key for storing logs in localStorage
     * @returns Tamper-evident logger
     */
    static createTamperEvidentLogger(key?: string, storageKey?: string): TamperEvidentLogger;
    /**
     * Get log level enum for tamper-evident logging
     * @returns Log level enum
     */
    static getLogLevel(): typeof LogLevel$1;
    /**
     * Perform secure modular exponentiation resistant to timing attacks
     *
     * @param base - Base value
     * @param exponent - Exponent value
     * @param modulus - Modulus value
     * @returns (base^exponent) mod modulus
     */
    static secureModPow(base: bigint, exponent: bigint, modulus: bigint): bigint;
    /**
     * Perform a fault-resistant comparison of two buffers
     * This is resistant to fault injection attacks
     *
     * @param a - First buffer to compare
     * @param b - Second buffer to compare
     * @returns True if the buffers are equal
     */
    static faultResistantEqual(a: Uint8Array, b: Uint8Array): boolean;
    /**
     * Generate a Ring-LWE key pair for post-quantum encryption
     *
     * @returns Public and private key pair
     */
    static generateRingLweKeypair(): any;
    /**
     * Encrypt data using Ring-LWE post-quantum encryption
     *
     * @param message - Message to encrypt
     * @param publicKey - Public key
     * @returns Encrypted message
     */
    static ringLweEncrypt(message: string | Uint8Array, publicKey: string): string;
    /**
     * Decrypt data using Ring-LWE post-quantum encryption
     *
     * @param ciphertext - Encrypted message
     * @param privateKey - Private key
     * @returns Decrypted message
     */
    static ringLweDecrypt(ciphertext: string, privateKey: string): Uint8Array;
    /**
     * Trigger a canary token
     *
     * @param token - Canary token to trigger
     * @param triggerContext - Additional context for the trigger
     * @returns True if the canary was triggered
     */
    static triggerCanaryToken(token: string, triggerContext?: any): boolean;
    /**
     * Encrypt data (uses AES-256-GCM by default)
     * @param data data to encrypt
     * @param key encryption key
     */
    static encrypt(data: any, key: string, options?: EncryptionOptions): Promise<string>;
    /**
     * Decrypt data (uses AES-256-GCM by default)
     * @param data data to encrypt
     * @param key encryption key
     */
    static decrypt(...p: Parameters<typeof EncryptionService.decrypt>): Promise<string>;
}

/**
 * Legacy Keys implementation for key derivation and management.
 * This class provides a backward-compatible interface for key derivation while leveraging
 * the modern, optimized key derivation infrastructure. It serves as a facade to the {@link OptimizedKeys} class,
 * simplifying interaction with cryptographic key operations and providing environment insights.
 *
 * @remarks
 * - This class ensures compatibility with legacy systems while delegating core functionality to {@link OptimizedKeys}.
 * - All methods are static, allowing direct usage without instantiation.
 * - Designed to be thread-safe and efficient by reusing a singleton instance of {@link OptimizedKeys}.
 *
 * @public
 */

/**
 * ### Cryptographic Key Management
 *
 * Advanced key generation, derivation, and management utilities for
 * symmetric and asymmetric cryptographic operations.
 *
 * @example
 * ```typescript
 * import { Keys } from "xypriss-security";
 *
 * // Generate encryption key
 * const encryptionKey = Keys.generateEncryptionKey(256);
 *
 * // Derive key from password
 * const derivedKey = await Keys.deriveKey("password", "salt");
 * ```
 */
declare class Keys {
    /**
     * Derives a cryptographic key from the provided input using specified options.
     * This method delegates to the optimized key derivation system, ensuring high performance
     * and adherence to cryptographic best practices.
     *
     * @param input - The input data for key derivation, either a password (string) or raw bytes (Uint8Array).
     * @param options - Optional configuration for key derivation, including algorithm, iterations, and other parameters.
     *                  If omitted, default values are applied based on the underlying {@link OptimizedKeys} implementation.
     * @returns A hexadecimal string representing the derived cryptographic key.
     *
     * @example
     * ```typescript
     * const key = Keys.deriveKey('myPassword', { algorithm: 'PBKDF2', iterations: 100000 });
     * console.log(key); // Outputs: "a1b2c3d4e5f6..."
     * ```
     *
     * @remarks
     * - Throws an invalid input error if the input format is invalid or unsupported.
     * - The output length depends on the algorithm and options specified.
     * - For security, ensure the input is securely handled to prevent leakage.
     *
     * @public
     */
    static deriveKey(input: string | Uint8Array, options?: KeyDerivationOptions): string;
    /**
     * Retrieves performance metrics for key derivation operations.
     * Offers detailed insights into the efficiency and resource usage of the underlying
     * optimized key derivation system.
     *
     * @returns An object containing performance metrics, such as derivation time (ms) and memory usage (MB).
     *
     * @example
     * ```typescript
     * const metrics = Keys.getMetrics();
     * console.log(metrics); // Outputs: { derivationTimeMs: 10, memoryUsedMb: 2.5, operationsCount: 100, ... }
     * ```
     *
     * @remarks
     * - Metrics are aggregated from the {@link OptimizedKeys} instance and may include vendor-specific data.
     * - Useful for debugging and optimizing key derivation processes in performance-critical applications.
     *
     * @public
     */
    static getMetrics(): object;
    /**
     * Retrieves information about the current runtime environment.
     * Includes details about such the as platform, supported cryptographic algorithms,
     * and other environment-specific data relevant to key derivation.
     *
     * @returns An object containing environment-specific information, such as platform type and cryptographic capabilities.
     *
     * @example
     * ```typescript
     * const envInfo = Keys.getEnvironmentInfo();
     * console.log('envInfo); // Outputs: ' { platform: 'Node.js', cryptoSupport: ['PBKDF2', 'Argon2'], version: '18.x', ... }
     * ```
     *
     * @remarks
     * - The exact structure of the returned object may vary depending on the runtime environment.
     * - Useful for feature detection and compatibility checks in cross-platform applications.
     *
     * @public
     */
    static getEnvironmentInfo(): object;
    /**
     * Recommends an optimal key derivation algorithm based on the current runtime environment.
     * Evaluates the environment to suggest a secure algorithm and performant algorithm, prioritizing security.
     * security.
     *
     * @returns A string indicating the recommended key derivation algorithm (e.g., 'PBKDF2', 'Argon2').
     *
     * @example
     * ```typescript
     * const algorithm = Keys.getRecommendedAlgorithm();
     * console.log(algorithm); // Outputs: 'Argon2'
     * ```
     *
     * @remarks
     * - The recommendation is based on factors like CPU architecture, memory availability, and cryptographic library support.
     * - The recommended algorithm may differ across environments (e.g., browser vs. server).
     *
     * @public
     */
    static getRecommendedAlgorithm(): string;
}

/**
 * Validation utilities for security-related inputs
 */
declare class Validators {
    /**
     * Validate a token length
     * @param length - The length to validate
     * @param minLength - Minimum allowed length
     * @param maxLength - Maximum allowed length
     * @throws Error if the length is invalid
     */
    static validateLength(length: number, minLength?: number, maxLength?: number): void;
    /**
     * Validate a hash algorithm
     * @param algorithm - The algorithm to validate
     * @param allowedAlgorithms - List of allowed algorithms
     * @throws Error if the algorithm is invalid
     */
    static validateAlgorithm(algorithm: string, allowedAlgorithms?: string[]): void;
    /**
     * Validate iteration count
     * @param iterations - The iteration count to validate
     * @param minIterations - Minimum allowed iterations
     * @param maxIterations - Maximum allowed iterations
     * @throws Error if the iteration count is invalid
     */
    static validateIterations(iterations: number, minIterations?: number, maxIterations?: number): void;
    /**
     * Validate a salt
     * @param salt - The salt to validate
     * @throws Error if the salt is invalid
     */
    static validateSalt(salt: string | Uint8Array): void;
    /**
     * Validate an output format
     * @param format - The format to validate
     * @param allowedFormats - List of allowed formats
     * @throws Error if the format is invalid
     */
    static validateOutputFormat(format: string, allowedFormats?: string[]): void;
    /**
     * Validate an entropy level
     * @param entropy - The entropy level to validate
     * @param allowedLevels - List of allowed entropy levels
     * @throws Error if the entropy level is invalid
     */
    static validateEntropyLevel(entropy: string, allowedLevels?: string[]): void;
    /**
     * Validate an API key format
     * @param apiKey - The API key to validate
     * @param expectedPrefix - Optional expected prefix
     * @throws Error if the API key format is invalid
     */
    static validateAPIKey(apiKey: string, expectedPrefix?: string): void;
    /**
     * Validate a session token format
     * @param token - The session token to validate
     * @throws Error if the session token format is invalid
     */
    static validateSessionToken(token: string): void;
    /**
     * Validate a password strength
     * @param password - The password to validate
     * @param minLength - Minimum required length
     * @param requireUppercase - Whether uppercase letters are required
     * @param requireLowercase - Whether lowercase letters are required
     * @param requireNumbers - Whether numbers are required
     * @param requireSymbols - Whether symbols are required
     * @throws Error if the password is too weak
     */
    static validatePasswordStrength(password: string, minLength?: number, requireUppercase?: boolean, requireLowercase?: boolean, requireNumbers?: boolean, requireSymbols?: boolean): void;
}

/**
 * 🔐 Password Management Types & Interfaces
 *
 * Type definitions for the modular password management system
 */
/**
 * Password encryption algorithms supported
 */
declare enum PasswordAlgorithm {
    ARGON2ID = "argon2id",// Recommended for new applications
    ARGON2I = "argon2i",// Memory-hard, side-channel resistant
    ARGON2D = "argon2d",// Memory-hard, faster
    SCRYPT = "scrypt",// Alternative memory-hard function
    PBKDF2_SHA512 = "pbkdf2-sha512",// Traditional but secure
    BCRYPT_PLUS = "bcrypt-plus",// Enhanced bcrypt with additional layers
    MILITARY = "military"
}
/**
 * Password security levels
 */
declare enum PasswordSecurityLevel {
    STANDARD = "standard",// Good for most applications
    HIGH = "high",// Enhanced security
    MAXIMUM = "maximum",// Maximum security
    MILITARY = "military",// Military-grade security
    QUANTUM_RESISTANT = "quantum-resistant"
}
/**
 * Password hashing options
 */
interface PasswordHashOptions {
    algorithm?: PasswordAlgorithm;
    securityLevel?: PasswordSecurityLevel;
    iterations?: number;
    memorySize?: number;
    parallelism?: number;
    saltLength?: number;
    pepper?: string;
    encryptionKey?: string;
    quantumResistant?: boolean;
    timingSafe?: boolean;
    secureWipe?: boolean;
}
/**
 * Password verification result
 */
interface PasswordVerificationResult {
    isValid: boolean;
    needsRehash?: boolean;
    securityLevel: PasswordSecurityLevel;
    algorithm: PasswordAlgorithm;
    timeTaken: number;
    recommendations?: string[];
}
/**
 * Password hash metadata
 */
interface PasswordHashMetadata {
    algorithm: PasswordAlgorithm;
    securityLevel: PasswordSecurityLevel;
    iterations: number;
    memorySize?: number;
    parallelism?: number;
    saltLength: number;
    hasEncryption: boolean;
    hasPepper: boolean;
    timestamp: number;
    version: string;
}
/**
 * Password strength analysis result
 */
interface PasswordStrengthAnalysis {
    score: number;
    feedback: string[];
    entropy: number;
    estimatedCrackTime: string;
    vulnerabilities: string[];
    details: {
        length: number;
        hasUppercase: boolean;
        hasLowercase: boolean;
        hasNumbers: boolean;
        hasSymbols: boolean;
        hasRepeated: boolean;
        hasSequential: boolean;
        hasCommonPatterns: boolean;
    };
}
/**
 * Password generation options
 */
interface PasswordGenerationOptions {
    length?: number;
    includeUppercase?: boolean;
    includeLowercase?: boolean;
    includeNumbers?: boolean;
    includeSymbols?: boolean;
    excludeSimilar?: boolean;
    minStrengthScore?: number;
    customCharset?: string;
    excludeChars?: string;
    requireAll?: boolean;
}
/**
 * Password generation result
 */
interface PasswordGenerationResult {
    password: string;
    strength: PasswordStrengthAnalysis;
    metadata: {
        generatedAt: number;
        algorithm: string;
        entropy: number;
    };
}
/**
 * Migration result from other password systems
 */
interface PasswordMigrationResult {
    newHash: string;
    migrated: boolean;
    originalAlgorithm?: string;
    newAlgorithm: PasswordAlgorithm;
    securityImprovement: number;
    recommendations?: string[];
}
/**
 * Password policy configuration
 */
interface PasswordPolicy {
    minLength: number;
    maxLength: number;
    requireUppercase: boolean;
    requireLowercase: boolean;
    requireNumbers: boolean;
    requireSymbols: boolean;
    minStrengthScore: number;
    forbiddenPatterns: RegExp[];
    forbiddenWords: string[];
    maxAge?: number;
    preventReuse?: number;
}
/**
 * Password validation result
 */
interface PasswordValidationResult {
    isValid: boolean;
    violations: string[];
    score: number;
    suggestions: string[];
}
/**
 * Password storage options
 */
interface PasswordStorageOptions {
    encrypt?: boolean;
    encryptionKey?: string;
    compress?: boolean;
    includeMetadata?: boolean;
    format?: "compact" | "verbose";
}
/**
 * Password manager configuration
 */
interface PasswordManagerConfig {
    defaultAlgorithm: PasswordAlgorithm;
    defaultSecurityLevel: PasswordSecurityLevel;
    globalPepper?: string;
    encryptionKey?: string;
    policy?: PasswordPolicy;
    timingSafeVerification: boolean;
    secureMemoryWipe: boolean;
    enableMigration: boolean;
}
/**
 * Password audit result
 */
interface PasswordAuditResult {
    totalPasswords: number;
    weakPasswords: number;
    outdatedHashes: number;
    needsRehash: number;
    securityScore: number;
    recommendations: string[];
    details: {
        algorithmDistribution: Record<PasswordAlgorithm, number>;
        securityLevelDistribution: Record<PasswordSecurityLevel, number>;
        averageStrength: number;
        oldestHash: number;
    };
}

/**
 * @author Supper Coder
 *  PasswordManager
 *
 * Main class for secure password management with modular architecture
 */
declare class PasswordManager {
    private static instance;
    private config;
    private algorithms;
    private security;
    private migration;
    private generator;
    private utils;
    private constructor();
    /**
     * Get singleton instance
     */
    static getInstance(config?: Partial<PasswordManagerConfig>): PasswordManager;
    /**
     * Create a new instance (for multiple configurations)
     */
    static create(config?: Partial<PasswordManagerConfig>): PasswordManager;
    /**
     * Hash a password with advanced security
     */
    hash(password: string, options?: PasswordHashOptions): Promise<string>;
    /**
     * Verify a password against a hash
     */
    verify(password: string, hash: string): Promise<PasswordVerificationResult>;
    /**
     * Generate a secure password
     */
    generatePassword(options?: any): PasswordGenerationResult;
    /**
     * Analyze password strength
     */
    analyzeStrength(password: string): PasswordStrengthAnalysis;
    /**
     * Migrate from bcrypt or other systems
     */
    migrate(password: string, oldHash: string, options?: any): Promise<PasswordMigrationResult>;
    /**
     * Validate password against policy
     */
    validatePolicy(password: string): PasswordValidationResult;
    /**
     * Rehash password with updated security
     */
    rehash(password: string, oldHash: string, newOptions?: PasswordHashOptions): Promise<{
        newHash: string;
        upgraded: boolean;
    }>;
    /**
     * Audit password security
     */
    auditSecurity(hashes: string[]): Promise<PasswordAuditResult>;
    /**
     * Configure global settings
     */
    configure(config: Partial<PasswordManagerConfig>): void;
    /**
     * Get current configuration
     */
    getConfig(): PasswordManagerConfig;
    private mergeOptions;
    private applyPepper;
    private createMetadata;
    private shouldRehash;
    private generateRecommendations;
    private constantTimeDelay;
}

/**
 * 🔐 Password Algorithms Module
 *
 * Implements various password hashing algorithms with security optimizations
 */

/**
 * Password hashing algorithms implementation
 */
declare class PasswordAlgorithms {
    private config;
    constructor(config: PasswordManagerConfig);
    /**
     * Update configuration
     */
    updateConfig(config: PasswordManagerConfig): void;
    /**
     * Hash password using specified algorithm
     */
    hash(password: string, salt: Uint8Array, options: PasswordHashOptions): Promise<string>;
    /**
     * Verify password using specified algorithm
     */
    verify(password: string, hash: string, salt: Uint8Array, metadata: PasswordHashMetadata): Promise<boolean>;
    /**
     * Hash with Argon2 (recommended)
     */
    private hashWithArgon2;
    /**
     * Hash with scrypt
     */
    private hashWithScrypt;
    /**
     * Hash with PBKDF2-SHA512
     */
    private hashWithPBKDF2;
    /**
     * Enhanced PBKDF2 with multiple rounds and algorithms
     */
    private hashWithEnhancedPBKDF2;
    /**
     * Enhanced bcrypt with additional security layers
     */
    private hashWithBcryptPlus;
    /**
     * Military-grade multi-layer hashing
     */
    private hashWithMilitary;
    /**
     * Extract just the hash value from complex hash formats
     */
    private extractHashValue;
    /**
     * Get algorithm-specific default options
     */
    getAlgorithmDefaults(algorithm: PasswordAlgorithm): PasswordHashOptions;
    /**
     * Estimate hashing time for algorithm
     */
    estimateHashingTime(algorithm: PasswordAlgorithm, options: PasswordHashOptions): number;
}

/**
 * 🔐 Password Security Analysis Module
 *
 * Production-ready password strength analysis and security validation
 */

/**
 * Password security analysis and validation
 */
declare class PasswordSecurity {
    private config;
    private commonPasswords;
    private keyboardPatterns;
    constructor(config: PasswordManagerConfig);
    /**
     * Update configuration
     */
    updateConfig(config: PasswordManagerConfig): void;
    /**
     * Analyze password strength with detailed metrics
     */
    analyzeStrength(password: string): PasswordStrengthAnalysis;
    /**
     * Validate password against policy
     */
    validatePolicy(password: string): PasswordValidationResult;
    /**
     * Audit multiple passwords for security issues
     */
    auditPasswords(hashes: string[]): Promise<PasswordAuditResult>;
    private getCommonPasswords;
    private getKeyboardPatterns;
    private createEmptyAnalysis;
    private analyzePasswordDetails;
    private calculateEntropy;
    private calculateStrengthScore;
    private findVulnerabilities;
    private generateFeedback;
    private estimateCrackTime;
    private hasSequentialChars;
    private hasCommonPatterns;
    private parseHashMetadata;
    private parseXyPrissHash;
    private parseBcryptHash;
    private parseArgon2Hash;
    private parseScryptHash;
    private parsePBKDF2Hash;
    private parseGenericHash;
    private extractIterationsFromPBKDF2;
    private isOutdatedAlgorithm;
    private isWeakHash;
    private getSecurityLevelScore;
}

/**
 * 🔐 Password Migration Module
 *
 * Handles migration from bcrypt and other password systems
 */

/**
 * Password migration utilities
 */
declare class PasswordMigration {
    private config;
    constructor(config: PasswordManagerConfig);
    /**
     * Update configuration
     */
    updateConfig(config: PasswordManagerConfig): void;
    /**
     * Migrate from bcrypt to XyPrissSecurity
     */
    fromBcrypt(password: string, bcryptHash: string, newOptions?: PasswordHashOptions): Promise<PasswordMigrationResult>;
    /**
     * Migrate from PBKDF2
     */
    fromPBKDF2(password: string, pbkdf2Hash: string, iterations: number, newOptions?: PasswordHashOptions): Promise<PasswordMigrationResult>;
    /**
     * Migrate from plain text (emergency use only)
     */
    fromPlainText(password: string, newOptions?: PasswordHashOptions): Promise<PasswordMigrationResult>;
    /**
     * Batch migration utility
     */
    batchMigrate(passwords: Array<{
        password: string;
        oldHash: string;
        algorithm: string;
    }>, newOptions?: PasswordHashOptions): Promise<PasswordMigrationResult[]>;
    /**
     * Generate migration report
     */
    generateMigrationReport(results: PasswordMigrationResult[]): {
        totalPasswords: number;
        successfulMigrations: number;
        failedMigrations: number;
        averageSecurityImprovement: number;
        recommendations: string[];
    };
    private calculateSecurityImprovement;
}

/**
 * 🔐 Password Generator Module
 *
 * Secure password generation with customizable requirements
 */

/**
 * Secure password generation
 */
declare class PasswordGenerator {
    private config;
    private security;
    constructor(config: PasswordManagerConfig);
    /**
     * Update configuration
     */
    updateConfig(config: PasswordManagerConfig): void;
    /**
     * Generate a secure password
     */
    generate(options?: PasswordGenerationOptions): PasswordGenerationResult;
    /**
     * Generate multiple passwords
     */
    generateBatch(count: number, options?: PasswordGenerationOptions): PasswordGenerationResult[];
    /**
     * Generate passphrase (word-based password)
     */
    generatePassphrase(options?: {
        wordCount?: number;
        separator?: string;
        includeNumbers?: boolean;
        includeSymbols?: boolean;
        minStrengthScore?: number;
    }): PasswordGenerationResult;
    /**
     * Generate PIN (numeric password)
     */
    generatePIN(length?: number): string;
    /**
     * Generate memorable password (pronounceable)
     */
    generateMemorable(options?: {
        length?: number;
        includeNumbers?: boolean;
        includeSymbols?: boolean;
        minStrengthScore?: number;
    }): PasswordGenerationResult;
    private mergeOptions;
    private generatePassword;
    private ensureAllCharacterTypes;
    private hasObviousPattern;
    /**
     * Returns a comprehensive word list for secure passphrase generation
     * Based on EFF's long wordlist for maximum security (2048 words = 11 bits entropy per word)
     */
    private getSecureWordList;
}

/**
 * 🔐 Password Utilities Module
 *
 * Utility functions for password management
 */

/**
 * Password utility functions
 */
declare class PasswordUtils {
    private config;
    constructor(config: PasswordManagerConfig);
    /**
     * Update configuration
     */
    updateConfig(config: PasswordManagerConfig): void;
    /**
     * Combine hash with metadata for storage
     */
    combineHashWithMetadata(hash: string, salt: Uint8Array, metadata: PasswordHashMetadata): string;
    /**
     * Parse hash with metadata from storage format
     */
    parseHashWithMetadata(combinedHash: string): {
        hash: string;
        salt: Uint8Array;
        metadata: PasswordHashMetadata;
    };
    /**
     * Encrypt password hash for storage
     */
    encryptPasswordHash(hash: string, encryptionKey: string): Promise<string>;
    /**
     * Decrypt password hash from storage
     */
    decryptPasswordHash(encryptedHash: string, encryptionKey: string): Promise<string>;
    /**
     * Check if hash is encrypted
     */
    isEncryptedHash(hash: string): boolean;
    /**
     * Compress password hash for storage efficiency
     */
    compressHash(hash: string): string;
    /**
     * Decompress password hash
     */
    decompressHash(compressedHash: string): string;
    /**
     * Format hash for different storage systems
     */
    formatForStorage(hash: string, options?: PasswordStorageOptions): string;
    /**
     * Validate hash format
     */
    validateHashFormat(hash: string): {
        isValid: boolean;
        format: string;
        errors: string[];
    };
    /**
     * Generate hash identifier for tracking
     */
    generateHashId(hash: string): string;
    /**
     * Estimate storage size
     */
    estimateStorageSize(hash: string, options?: PasswordStorageOptions): {
        originalSize: number;
        finalSize: number;
        compression: number;
        overhead: number;
    };
    private deriveEncryptionKey;
    private simpleEncrypt;
    private simpleDecrypt;
    /**
     * Synchronous encryption for password hashes
     * @param hash - Hash to encrypt
     * @param encryptionKey - Encryption key
     * @returns Encrypted hash
     */
    private encryptPasswordHashSync;
    /**
     * Synchronous key derivation
     * @param password - Password to derive key from
     * @returns Derived key
     */
    private deriveEncryptionKeySync;
    /**
     * Apply multi-stage compression for maximum efficiency
     * Uses a combination of LZ77-like compression and entropy encoding
     */
    private applyMultiStageCompression;
    /**
     * Dictionary-based compression similar to LZ77
     */
    private applyDictionaryCompression;
    /**
     * Run-length encoding for repeated bytes
     */
    private applyRunLengthEncoding;
    /**
     * Frequency-based encoding (simplified Huffman)
     */
    private applyFrequencyEncoding;
    /**
     * Apply multi-stage decompression (reverse of compression)
     */
    private applyMultiStageDecompression;
    /**
     * Reverse frequency encoding
     */
    private reverseFrequencyEncoding;
    /**
     * Reverse run-length encoding
     */
    private reverseRunLengthEncoding;
    /**
     * Reverse dictionary compression
     */
    private reverseDictionaryCompression;
}

/**
 * XyPrissSecurity Password Management Module => FPMM
 *
 * Modular, military-grade password management system
 *
 * @example
 * ```typescript
 * import { PasswordManager } from "xypriss-security/core/password";
 *
 * // Create password manager instance
 * const pm = PasswordManager.getInstance();
 *
 * // Hash a password
 * const hash = await pm.hash("mySecurePassword123!");
 *
 * // Verify a password
 * const result = await pm.verify("mySecurePassword123!", hash);
 * console.log(result.isValid); // true
 *
 * // Generate secure password
 * const generated = pm.generatePassword({ length: 16, minStrengthScore: 90 });
 * console.log(generated.password);
 *
 * // Migrate from bcrypt
 * const migration = await pm.migrate("password", bcryptHash);
 * if (migration.migrated) {
 *     console.log("Successfully migrated to XyPrissSecurity!");
 * }
 * ```
 */

/**
 * Quick hash function for simple use cases
 */
declare function hashPassword(password: string, options?: PasswordHashOptions): Promise<string>;
/**
 * Quick verify function for simple use cases
 */
declare function verifyPassword(password: string, hash: string): Promise<boolean>;
/**
 * Quick password generation for simple use cases
 */
declare function generateSecurePassword(options?: any): any;
/**
 * Quick password strength analysis
 */
declare function analyzePasswordStrength(password: string): any;
/**
 * Quick bcrypt migration
 */
declare function migrateBcryptPassword(password: string, bcryptHash: string, options?: any): Promise<any>;
/**
 * Create a configured password manager instance
 */
declare function createPasswordManager(config?: Partial<PasswordManagerConfig>): PasswordManager;
/**
 * Get default password policy
 */
declare function getDefaultPasswordPolicy(): PasswordPolicy;
/**
 * Get recommended security configuration
 */
declare function getRecommendedConfig(): any;
/**
 * Get military-grade security configuration
 */
declare function getMilitaryConfig(): any;
/**
 * bcrypt-compatible hash function
 * Drop-in replacement for bcrypt.hash()
 */
declare function hash(password: string, saltRounds?: number): Promise<string>;
/**
 * bcrypt-compatible compare function
 * Drop-in replacement for bcrypt.compare()
 */
declare function compare(password: string, hash: string): Promise<boolean>;
/**
 * Generate salt (bcrypt compatibility)
 */
declare function genSalt(rounds?: number): string;
/**
 * Batch password operations
 */
declare class PasswordBatch {
    private pm;
    constructor(config?: Partial<PasswordManagerConfig>);
    /**
     * Hash multiple passwords
     */
    hashMany(passwords: string[], options?: PasswordHashOptions): Promise<string[]>;
    /**
     * Verify multiple passwords
     */
    verifyMany(passwordHashPairs: Array<{
        password: string;
        hash: string;
    }>): Promise<boolean[]>;
    /**
     * Generate multiple passwords
     */
    generateMany(count: number, options?: PasswordGenerationOptions): PasswordGenerationResult[];
}
/**
 * Default password manager instance
 * Ready to use out of the box
 */
declare const defaultPasswordManager: PasswordManager;
/**
 * Legacy class name for backward compatibility
 * @deprecated Use PasswordManager instead
 */
declare const SecurePasswordManager: typeof PasswordManager;

/***************************************************************************
 * XyPrissSecurity - Secure Array Types
 *
 * This file contains type definitions for the SecureArray modular architecture
 *
 * @author Nehonix
 *
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */
/**
 * Type definitions for SecureArray modular architecture
 */

/**
 * Types that can be stored securely in arrays
 */
type SecureArrayValue = string | number | boolean | Uint8Array | SecureString | SecureObject<any> | null | undefined | object;
/**
 * Serialization options for SecureArray
 */
interface SecureArraySerializationOptions {
    includeMetadata?: boolean;
    encryptSensitive?: boolean;
    format?: "json" | "binary" | "compact" | "base64";
    preserveOrder?: boolean;
    compression?: boolean;
    includeChecksum?: boolean;
}
/**
 * Metadata for tracking secure array elements
 */
interface ElementMetadata {
    type: string;
    isSecure: boolean;
    created: Date;
    lastAccessed: Date;
    accessCount: number;
    index: number;
}
/**
 * Event types for SecureArray
 */
type SecureArrayEvent = "created" | "push" | "pop" | "shift" | "unshift" | "splice" | "sort" | "reverse" | "get" | "set" | "clear" | "destroy" | "filtered" | "mapped" | "reduced" | "gc" | "encrypt_all" | "slice" | "snapshot_created" | "snapshot_restored" | "freeze" | "unfreeze" | "readonly" | "writable" | "destroyed" | "compact" | "unique" | "shuffle";
/**
 * Event listener callback for SecureArray
 */
type SecureArrayEventListener = (event: SecureArrayEvent, index?: number, value?: any, metadata?: any) => void | Promise<void>;
/**
 * Configuration options for SecureArray
 */
interface SecureArrayOptions {
    readOnly?: boolean;
    autoDestroy?: boolean;
    encryptionKey?: string;
    maxMemory?: number;
    gcThreshold?: number;
    enableMemoryTracking?: boolean;
    autoCleanup?: boolean;
    maxLength?: number;
    maxSize?: number;
    enableIndexValidation?: boolean;
    enableTypeValidation?: boolean;
}
/**
 * Statistics for SecureArray performance monitoring
 */
interface SecureArrayStats {
    length: number;
    secureElements: number;
    totalAccesses: number;
    memoryUsage: number;
    lastModified: number;
    version: number;
    createdAt: number;
    isReadOnly: boolean;
    isFrozen: boolean;
    typeDistribution: Record<string, number>;
    secureElementCount: number;
    estimatedMemoryUsage: number;
    snapshotCount: number;
    encryptionEnabled: boolean;
}
/**
 * Helper type for creating flexible SecureArray instances
 */
type FlexibleSecureArray<T = SecureArrayValue> = T[] & {
    [key: string]: any;
};
/**
 * Predicate function type for filtering and searching
 */
type PredicateFn<T extends SecureArrayValue> = (value: T, index: number, array: SecureArray<T>) => boolean;
/**
 * Comparator function type for sorting
 */
type ComparatorFn<T extends SecureArrayValue> = (a: T, b: T) => number;
/**
 * Mapper function type for transformations
 */
type MapperFn<T extends SecureArrayValue, U> = (value: T, index: number, array: SecureArray<T>) => U;
/**
 * Reducer function type for aggregations
 */
type ReducerFn<T extends SecureArrayValue, U> = (accumulator: U, currentValue: T, currentIndex: number, array: SecureArray<T>) => U;

/***************************************************************************
 * XyPrissSecurity - Enhanced Secure Array Core Implementation
 *
 *  security features and array methods
 *
 * @author Nehonix & Community
 *
 * @license MIT
 ***************************************************************************** */

/**
 * A secure array that can store sensitive data with enhanced security features
 * T represents the type of elements stored in the array
 */
declare class SecureArray<T extends SecureArrayValue = SecureArrayValue> implements Iterable<T> {
    private elements;
    private secureBuffers;
    private metadataManager;
    private eventManager;
    private cryptoHandler;
    private serializationHandler;
    private _isDestroyed;
    private _isReadOnly;
    private _isFrozen;
    private readonly _id;
    private _version;
    private _lastModified;
    private _createdAt;
    private _memoryTracking;
    private secureBufferPool?;
    private _maxSize?;
    private options;
    private snapshots;
    /**
     * Creates a new secure array
     */
    constructor(initialData?: T[], options?: SecureArrayOptions);
    /**
     * Initialize secure buffer pool for efficient memory reuse
     */
    private initializeSecureBufferPool;
    /**
     * Handle memory pressure by cleaning up unused resources
     */
    private handleMemoryPressure;
    /**
     * Secure wipe of buffer contents
     */
    private secureWipe;
    /**
     * Ensures the array is not destroyed
     */
    private ensureNotDestroyed;
    /**
     * Ensures the array is not read-only
     */
    private ensureNotReadOnly;
    /**
     * Ensures the array is not frozen
     */
    private ensureNotFrozen;
    /**
     * Check if adding elements would exceed max size
     */
    private checkSizeLimit;
    /**
     * Updates the last modified timestamp and version
     */
    private updateLastModified;
    /**
     * Validates an index
     */
    private validateIndex;
    /**
     * Validates a value
     */
    private validateValue;
    /**
     * Gets the length of the array
     */
    get length(): number;
    /**
     * Gets the unique identifier of this array
     */
    get id(): string;
    /**
     * Gets the version number (increments on each mutation)
     */
    get version(): number;
    /**
     * Gets when the array was last modified
     */
    get lastModified(): number;
    /**
     * Gets when the array was created
     */
    get createdAt(): number;
    /**
     * Check if the array is empty
     */
    get isEmpty(): boolean;
    /**
     * Check if the array is read-only
     */
    get isReadOnly(): boolean;
    /**
     * Check if the array is frozen
     */
    get isFrozen(): boolean;
    /**
     * Check if the array is destroyed
     */
    get isDestroyed(): boolean;
    /**
     * Gets an element at the specified index with automatic decryption
     */
    get(index: number): T | undefined;
    /**
     * Gets element at index with bounds checking
     */
    at(index: number): T | undefined;
    /**
     * Sets an element at the specified index
     */
    set(index: number, value: T): this;
    /**
     * Cleans up resources associated with an index
     */
    private cleanupIndex;
    /**
     * Adds an element to the end of the array
     */
    push(value: T): number;
    /**
     * Removes and returns the last element
     */
    pop(): T | undefined;
    /**
     * Removes and returns the first element
     */
    shift(): T | undefined;
    /**
     * Adds elements to the beginning of the array
     */
    unshift(...values: T[]): number;
    /**
     * Adds multiple elements to the array
     */
    pushAll(values: T[]): number;
    /**
     * Removes elements from array and optionally inserts new elements
     */
    splice(start: number, deleteCount?: number, ...items: T[]): SecureArray<T>;
    /**
     * Returns a shallow copy of a portion of the array
     */
    slice(start?: number, end?: number): SecureArray<T>;
    /**
     * Concatenates arrays and returns a new SecureArray
     */
    concat(...arrays: (T[] | SecureArray<T>)[]): SecureArray<T>;
    /**
     * Joins all elements into a string
     */
    join(separator?: string): string;
    /**
     * Reverses the array in place
     */
    reverse(): this;
    /**
     * Sorts the array in place
     */
    sort(compareFn?: ComparatorFn<T>): this;
    /**
     * Calls a function for each element
     */
    forEach(callback: (value: T, index: number, array: SecureArray<T>) => void, thisArg?: any): void;
    /**
     * Creates a new array with results of calling a function for every element
     */
    map<U extends SecureArrayValue>(callback: MapperFn<T, U>, thisArg?: any): SecureArray<U>;
    /**
     * Creates a new array with elements that pass a test
     */
    filter(predicate: PredicateFn<T>, thisArg?: any): SecureArray<T>;
    /**
     * Reduces the array to a single value
     */
    reduce<U>(callback: ReducerFn<T, U>, initialValue?: U): U;
    /**
     * Tests whether at least one element passes the test
     */
    some(predicate: PredicateFn<T>, thisArg?: any): boolean;
    /**
     * Tests whether all elements pass the test
     */
    every(predicate: PredicateFn<T>, thisArg?: any): boolean;
    /**
     * Finds the first element that satisfies the predicate
     */
    find(predicate: PredicateFn<T>, thisArg?: any): T | undefined;
    /**
     * Finds the index of the first element that satisfies the predicate
     */
    findIndex(predicate: PredicateFn<T>, thisArg?: any): number;
    /**
     * Finds the last element that satisfies the predicate
     */
    findLast(predicate: PredicateFn<T>, thisArg?: any): T | undefined;
    /**
     * Finds the index of the last element that satisfies the predicate
     */
    findLastIndex(predicate: PredicateFn<T>, thisArg?: any): number;
    /**
     * Returns the first index of an element
     */
    indexOf(searchElement: T, fromIndex?: number): number;
    /**
     * Returns the last index of an element
     */
    lastIndexOf(searchElement: T, fromIndex?: number): number;
    /**
     * Checks if an element exists in the array
     */
    includes(searchElement: T, fromIndex?: number): boolean;
    /**
     * Creates a snapshot of the current array state
     */
    createSnapshot(name?: string): string;
    /**
     * Restores the array from a snapshot
     */
    restoreFromSnapshot(snapshotId: string): boolean;
    /**
     * Lists available snapshots
     */
    listSnapshots(): Array<{
        id: string;
        timestamp: number;
    }>;
    /**
     * Deletes a snapshot
     */
    deleteSnapshot(snapshotId: string): boolean;
    /**
     * Clears all elements from the array
     */
    clear(): this;
    /**
     * Freezes the array to prevent modifications
     */
    freeze(): this;
    /**
     * Unfreezes the array to allow modifications
     */
    unfreeze(): this;
    /**
     * Makes the array read-only
     */
    makeReadOnly(): this;
    /**
     * Removes read-only restriction
     */
    makeWritable(): this;
    /**
     * Securely wipes all data and destroys the array
     * @example
     * //===================== correct ===========
        const x = fArray([] as number[]);
        x.push(12);

        console.log(x._array);
        x.destroy();

        //================ incorrect ===============
        const x = fArray([] as number[]);
        x.destroy(); // will destroy the array
        x.push(12); // x.push will throw an error

        console.log(x._array); // will throw an error
     */
    destroy(): void;
    /**
     * Gets comprehensive statistics about the array
     */
    getStats(): SecureArrayStats;
    /**
     * Validates the integrity of the array
     */
    validateIntegrity(): {
        isValid: boolean;
        errors: string[];
    };
    /**
     * Compacts the array by removing undefined/null elements
     */
    compact(): this;
    /**
     * Removes duplicate elements
     */
    unique(): this;
    /**
     * Groups elements by a key function
     */
    groupBy<K extends string | number>(keyFn: (value: T, index: number) => K): Map<K, SecureArray<T>>;
    /**
     * Returns the minimum value
     */
    min(compareFn?: ComparatorFn<T>): T | undefined;
    /**
     * Returns the maximum value
     */
    max(compareFn?: ComparatorFn<T>): T | undefined;
    /**
     * Shuffles the array in place using Fisher-Yates algorithm
     */
    shuffle(): this;
    /**
     * Returns a random sample of elements
     */
    sample(count?: number): SecureArray<T>;
    /**
     * Returns an iterator for the array
     */
    [Symbol.iterator](): Iterator<T>;
    /**
     * Returns an iterator for array entries [index, value]
     */
    entries(): Iterator<[number, T]>;
    /**
     * Returns an iterator for array indices
     */
    keys(): Iterator<number>;
    /**
     * Returns an iterator for array values
     */
    values(): Iterator<T>;
    /**
     * Adds an event listener
     */
    on(event: SecureArrayEvent, listener: SecureArrayEventListener): this;
    /**
     * Removes an event listener
     */
    off(event: SecureArrayEvent, listener: SecureArrayEventListener): this;
    /**
     * Adds a one-time event listener
     */
    once(event: SecureArrayEvent, listener: SecureArrayEventListener): this;
    /**
     * Serializes the SecureArray to a secure format
     */
    serialize(options?: SecureArraySerializationOptions): string;
    /**
     * Exports the SecureArray data in various formats
     */
    exportData(format?: "json" | "csv" | "xml" | "yaml"): string;
    /**
     * Converts to a regular JavaScript array (loses security features)
     */
    toArray(): T[];
    /**
     * Converts to a regular JavaScript array (same as toArray method)
     */
    get _array(): T[];
    /**
     * Creates a SecureArray from a regular array
     */
    static from<T extends SecureArrayValue>(arrayLike: ArrayLike<T> | Iterable<T>, options?: SecureArrayOptions): SecureArray<T>;
    /**
     * Creates a SecureArray with specified length and fill value
     */
    static of<T extends SecureArrayValue>(...elements: T[]): SecureArray<T>;
    /**
     * Gets encryption status from the crypto handler
     */
    getEncryptionStatus(): {
        isInitialized: boolean;
        hasEncryptionKey: boolean;
        algorithm: string;
    };
    /**
     * Sets an encryption key for the array
     */
    setEncryptionKey(key: string): void;
    /**
     * Gets the raw encrypted data without decryption (for verification)
     */
    getRawEncryptedData(): any[];
    /**
     * Gets a specific element's raw encrypted form (for verification)
     */
    getRawEncryptedElement(index: number): any;
    /**
     * Encrypts all elements in the array using AES-256-CTR-HMAC encryption
     * with proper memory management and atomic operations
     */
    encryptAll(): this;
}

/***************************************************************************
 * XyPrissSecurity - Secure Array Main Export
 *
 * This file contains the main exports for the SecureArray module
 *
 * @author Nehonix
 *
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */
/**
 * Main export file for SecureArray
 */

type WidenLiterals<T> = T extends string ? string : T extends number ? number : T extends boolean ? boolean : T;
/**
 * Creates a SecureArray with initial data
 */
declare function createSecureArray<T extends SecureArrayValue = SecureArrayValue>(initialData?: WidenLiterals<T>[], options?: SecureArrayOptions): SecureArray<WidenLiterals<T>>;

/**
 * Side-Channel Attack Protection Module
 *
 * This module provides protection against various side-channel attacks:
 * - Timing attacks: Ensures operations take constant time regardless of input
 * - Cache attacks: Implements cache-resistant operations
 * - Power analysis: Reduces power analysis vectors through balanced operations
 * - Fault injection: Detects and mitigates fault injection attempts
 */
/**
 * Performs a constant-time comparison of two strings or arrays
 * Prevents timing attacks by ensuring the comparison takes the same amount of time
 * regardless of how many characters match
 *
 * @param a - First string or array to compare
 * @param b - Second string or array to compare
 * @returns True if the inputs are equal, false otherwise
 */
declare function constantTimeEqual(a: string | Uint8Array, b: string | Uint8Array): boolean;
/**
 * Performs a masked memory access to prevent cache-timing attacks
 * This technique helps mitigate cache-based side-channel attacks by
 * accessing all elements of an array regardless of which one is needed
 *
 * @param array - Array to access
 * @param index - Index to retrieve
 * @returns The value at the specified index
 */
declare function maskedAccess<T>(array: T[], index: number): T;
/**
 * Implements a secure modular exponentiation algorithm resistant to timing attacks
 * Used for cryptographic operations like RSA and Diffie-Hellman
 *
 * @param base - Base value
 * @param exponent - Exponent value
 * @param modulus - Modulus value
 * @returns (base^exponent) mod modulus
 */
declare function secureModPow(base: bigint, exponent: bigint, modulus: bigint): bigint;
/**
 * Implements a secure memory comparison that's resistant to fault injection attacks
 * This performs multiple comparisons and verifies the results match to detect glitches
 *
 * @param a - First buffer to compare
 * @param b - Second buffer to compare
 * @returns True if the buffers are equal, false otherwise
 */
declare function faultResistantEqual(a: Uint8Array, b: Uint8Array): boolean;
/**
 * Creates a secure random delay to mitigate timing attacks
 * This adds unpredictable timing variations to make it harder
 * to extract information through precise timing measurements
 *
 * @param minMs - Minimum delay in milliseconds
 * @param maxMs - Maximum delay in milliseconds
 * @returns Promise that resolves after the random delay
 */
declare function randomDelay(minMs?: number, maxMs?: number): Promise<void>;
/**
 * Applies cache-hardening to a function to protect against cache-timing attacks
 * This technique ensures the function accesses the same memory regions
 * regardless of input, making cache-timing attacks more difficult
 *
 * @param fn - Function to protect
 * @returns Cache-hardened version of the function
 */
declare function cacheHarden<T extends (...args: any[]) => any>(fn: T): T;

/**
 * Options for memory-hard key derivation
 */
interface MemoryHardOptions {
    /**
     * Memory cost parameter (higher = more memory usage)
     * @default 16384 (16 MB)
     */
    memoryCost?: number;
    /**
     * Time cost parameter (higher = more iterations)
     * @default 4
     */
    timeCost?: number;
    /**
     * Parallelism parameter (higher = more threads if available)
     * @default 1
     */
    parallelism?: number;
    /**
     * Output key length in bytes
     * @default 32
     */
    keyLength?: number;
    /**
     * Salt for the derivation
     * If not provided, a random salt will be generated
     */
    salt?: Uint8Array;
    /**
     * Salt length in bytes (if generating a new salt)
     * @default 16
     */
    saltLength?: number;
}
/**
 * Result of memory-hard key derivation
 */
interface MemoryHardResult {
    /**
     * Derived key as a hex string
     */
    derivedKey: string;
    /**
     * Salt used for the derivation (hex encoded)
     */
    salt: string;
    /**
     * Parameters used for the derivation
     */
    params: {
        memoryCost: number;
        timeCost: number;
        parallelism: number;
        keyLength: number;
    };
    /**
     * Performance metrics
     */
    metrics: {
        /**
         * Time taken in milliseconds
         */
        timeTakenMs: number;
        /**
         * Estimated memory used in bytes
         */
        memoryUsedBytes: number;
    };
}
/**
 * Implements the Argon2 memory-hard key derivation function using the argon2 library
 *
 * Argon2 is designed to be resistant to GPU, ASIC, and FPGA attacks by
 * requiring large amounts of memory to compute.
 *
 * This implementation uses the official argon2 library for Node.js.
 *
 * @param password - Password to derive key from
 * @param options - Derivation options
 * @returns Derived key and metadata
 */
declare function argon2Derive(password: string | Uint8Array, options?: MemoryHardOptions): Promise<MemoryHardResult>;
/**
 * Implements a real version of the Balloon memory-hard hashing algorithm
 *
 * Balloon is designed to be a simple memory-hard algorithm with provable
 * memory-hardness properties. This implementation follows the paper:
 * "Balloon: A Forward-Secure Password-Hashing Algorithm with Memory-Hard Functions"
 * by Dan Boneh, Henry Corrigan-Gibbs, and Stuart Schechter.
 *
 * @param password - Password to derive key from
 * @param options - Derivation options
 * @returns Derived key and metadata
 */
declare function balloonDerive(password: string | Uint8Array, options?: MemoryHardOptions): MemoryHardResult;

/**
 * Post-Quantum Cryptography Module
 *
 * This module provides cryptographic primitives that are believed to be
 * resistant to attacks by quantum computers. It implements versions
 * of lattice-based, hash-based, and code-based cryptography.
 *
 * Where possible, it uses standardized libraries for  implementations.
 * Fallback simplified implementations are provided for educational purposes and
 * environments where the libraries are not available.
 */
/**
 * Options for hash-based signatures
 */
interface HashBasedSignatureOptions {
    /**
     * Number of hash chains to use (higher = more secure but larger signatures)
     * @default 256
     */
    chainCount?: number;
    /**
     * Depth of each hash chain (higher = more secure but slower)
     * @default 16
     */
    chainDepth?: number;
}
/**
 * Result of key generation
 */
interface KeyPair {
    /**
     * Public key (hex encoded)
     */
    publicKey: string;
    /**
     * Private key (hex encoded)
     */
    privateKey: string;
}
/**
 * Parameters for post-quantum algorithms
 */
interface PostQuantumParams {
    /**
     * Security level (1, 3, or 5)
     * Higher levels provide more security but are slower and use more memory
     * @default 3
     */
    securityLevel?: number;
    /**
     * Additional algorithm-specific parameters
     */
    [key: string]: any;
}
/**
 * Post-quantum key pair with algorithm information
 */
interface PostQuantumKeyPair extends KeyPair {
    /**
     * Algorithm identifier
     */
    algorithm: string;
    /**
     * Algorithm parameters
     */
    params: Record<string, any>;
}
/**
 * Result of key encapsulation
 */
interface PostQuantumEncapsulation {
    /**
     * Ciphertext (hex encoded)
     */
    ciphertext: string;
    /**
     * Shared secret (hex encoded)
     */
    sharedSecret: string;
    /**
     * Algorithm identifier
     */
    algorithm: string;
    /**
     * Algorithm parameters
     */
    params: Record<string, any>;
}
/**
 * Result of key decapsulation
 */
interface PostQuantumDecapsulation {
    /**
     * Shared secret (hex encoded)
     */
    sharedSecret: string;
    /**
     * Algorithm identifier
     */
    algorithm: string;
    /**
     * Algorithm parameters
     */
    params: Record<string, any>;
}
/**
 * Implements a simplified Lamport one-time signature scheme
 * This is a hash-based signature scheme resistant to quantum attacks
 *
 * @param message - Message to sign
 * @param privateKey - Private key (hex encoded)
 * @returns Signature (hex encoded)
 */
declare function lamportSign(message: string | Uint8Array, privateKey: string): string;
/**
 * Verifies a Lamport signature
 *
 * @param message - Message that was signed
 * @param signature - Signature to verify (hex encoded)
 * @param publicKey - Public key (hex encoded)
 * @returns True if the signature is valid, false otherwise
 */
declare function lamportVerify(message: string | Uint8Array, signature: string, publicKey: string): boolean;
/**
 * Generates a Lamport key pair
 *
 * @returns Public and private key pair (hex encoded)
 */
declare function lamportGenerateKeypair(): KeyPair;
/**
 * Implements a simplified Ring-LWE encryption scheme
 * This is a lattice-based encryption scheme resistant to quantum attacks
 *
 * Note: This is a very simplified version for educational purposes
 *
 * @param message - Message to encrypt (must be 32 bytes or less)
 * @param publicKey - Public key (hex encoded)
 * @returns Encrypted message (hex encoded)
 */
declare function ringLweEncrypt(message: string | Uint8Array, publicKey: string): string;
/**
 * Decrypts a message encrypted with Ring-LWE
 *
 * @param ciphertext - Encrypted message (hex encoded)
 * @param privateKey - Private key (hex encoded)
 * @returns Decrypted message
 */
declare function ringLweDecrypt(ciphertext: string, privateKey: string): Uint8Array;
/**
 * Generates a Ring-LWE key pair
 *
 * @returns Public and private key pair (hex encoded)
 */
declare function ringLweGenerateKeypair(): KeyPair;
/**
 * Implements the Kyber key encapsulation mechanism (KEM)
 *
 * Kyber is a lattice-based key encapsulation mechanism that is believed to be
 * secure against quantum computer attacks.
 *
 * This implementation uses the crystals-kyber library, which provides a
 *  implementation of the Kyber algorithm.
 *
 * @param params - Parameters for the key generation
 * @returns Key pair with public and private keys
 */
declare function generateKyberKeyPair(params?: PostQuantumParams): PostQuantumKeyPair;
/**
 * Encapsulates a shared secret using a Kyber public key
 *
 * @param publicKey - Recipient's public key (hex encoded)
 * @param params - Optional parameters
 * @returns Encapsulated shared secret and ciphertext
 */
declare function kyberEncapsulate(publicKey: string, params?: PostQuantumParams): PostQuantumEncapsulation;
/**
 * Decapsulates a shared secret using a Kyber private key and ciphertext
 *
 * @param privateKey - Recipient's private key (hex encoded)
 * @param ciphertext - Ciphertext from encapsulation (hex encoded)
 * @param params - Optional parameters
 * @returns Decapsulated shared secret
 */
declare function kyberDecapsulate(privateKey: string, ciphertext: string, params?: PostQuantumParams): PostQuantumDecapsulation;

/**
 * Canary Tokens Module
 *
 * This module provides functionality for creating and managing canary tokens,
 * which are special tokens that can detect unauthorized access or data breaches.
 *
 * Canary tokens can be embedded in sensitive data or systems, and when accessed,
 * they trigger alerts or other actions to notify of potential security breaches.
 */
/**
 * Canary token options
 */
interface CanaryOptions {
    /**
     * Callback function to execute when the canary is triggered
     */
    callback?: (context: any) => void;
    /**
     * URL to notify when the canary is triggered
     */
    notifyUrl?: string;
    /**
     * Context information to include with the canary
     */
    context?: any;
    /**
     * Secret key for the canary
     * If not provided, a random key will be generated
     */
    key?: string;
    /**
     * Expiration time in milliseconds
     * If not provided, the canary will not expire
     */
    expiresIn?: number;
}
/**
 * Creates a canary token
 *
 * @param options - Canary options
 * @returns Canary token
 */
declare function createCanary(options?: CanaryOptions): string;
/**
 * Triggers a canary token
 *
 * @param token - Canary token to trigger
 * @param context - Additional context for the trigger
 * @returns True if the canary was triggered successfully
 */
declare function triggerCanary(token: string, context?: any): boolean;
/**
 * Creates a canary object that triggers when accessed
 *
 * @param target - Object to wrap with a canary
 * @param options - Canary options
 * @returns Proxy object that triggers the canary when accessed
 */
declare function createCanaryObject<T extends object>(target: T, options?: CanaryOptions): T;
/**
 * Creates a canary function that triggers when called
 *
 * @param fn - Function to wrap with a canary
 * @param options - Canary options
 * @returns Function that triggers the canary when called
 */
declare function createCanaryFunction<T extends Function>(fn: T, options?: CanaryOptions): T;

/**
 * Attestation options
 */
interface AttestationOptions {
    /**
     * Key to use for signing
     * If not provided, a random key will be generated
     */
    key?: string;
    /**
     * Expiration time in milliseconds
     * If not provided, the attestation will not expire
     */
    expiresIn?: number;
    /**
     * Additional claims to include in the attestation
     */
    claims?: Record<string, any>;
    /**
     * Whether to include environment information
     * @default true
     */
    includeEnvironment?: boolean;
}
/**
 * Attestation verification options
 */
interface VerificationOptions {
    /**
     * Key to use for verification
     */
    key: string;
    /**
     * Whether to verify the expiration
     * @default true
     */
    verifyExpiration?: boolean;
    /**
     * Whether to verify the environment
     * @default false
     */
    verifyEnvironment?: boolean;
    /**
     * Required claims that must be present and match
     */
    requiredClaims?: Record<string, any>;
}
/**
 * Attestation result
 */
interface AttestationResult {
    /**
     * Whether the attestation is valid
     */
    valid: boolean;
    /**
     * Reason for invalidity, if any
     */
    reason?: string;
    /**
     * Claims from the attestation
     */
    claims?: Record<string, any>;
    /**
     * Environment information from the attestation
     */
    environment?: Record<string, any>;
    /**
     * Expiration time of the attestation
     */
    expiresAt?: number;
}
/**
 * Generates a key pair for attestation using asymmetric cryptography
 *
 * @returns Object containing public and private keys
 */
declare function generateAttestationKey(): {
    publicKey: string;
    privateKey: string;
};
/**
 * Creates an attestation for the given data
 *
 * @param data - Data to attest
 * @param options - Attestation options
 * @returns Attestation string
 */
declare function createAttestation(data: string | Uint8Array | Record<string, any>, options?: AttestationOptions): string;
/**
 * Verifies an attestation
 *
 * @param attestation - Attestation to verify
 * @param options - Verification options
 * @returns Verification result
 */
declare function verifyAttestation(attestation: string, options: VerificationOptions): AttestationResult;
/**
 * Creates an attestation for the library itself
 * This can be used to verify the integrity of the library
 *
 * @param options - Attestation options
 * @returns Attestation string
 */
declare function createLibraryAttestation(options?: AttestationOptions): string;
/**
 * Verifies a library attestation
 *
 * @param attestation - Attestation to verify
 * @param options - Verification options
 * @returns Verification result
 */
declare function verifyLibraryAttestation(attestation: string, options: VerificationOptions): AttestationResult;

/**
 * Runtime Security Verification Module
 *
 * This module provides functionality for verifying the security of the runtime
 * environment and detecting potential security issues or tampering attempts.
 *
 * It can detect debuggers, browser extensions that might intercept crypto operations,
 * compromised JavaScript environments, and other security threats.
 */
/**
 * Security verification result
 */
interface SecurityVerificationResult {
    /**
     * Whether the environment is secure
     */
    secure: boolean;
    /**
     * List of detected issues
     */
    issues: SecurityIssue[];
    /**
     * Overall security score (0-100)
     */
    score: number;
    /**
     * Detailed results for each check
     */
    checks: SecurityCheck[];
}
/**
 * Security issue
 */
interface SecurityIssue {
    /**
     * Issue type
     */
    type: SecurityIssueType;
    /**
     * Issue description
     */
    description: string;
    /**
     * Issue severity (0-100)
     */
    severity: number;
    /**
     * Potential mitigations
     */
    mitigations?: string[];
}
/**
 * Security issue type
 */
declare enum SecurityIssueType {
    DEBUGGER = "debugger",
    EXTENSION_INTERFERENCE = "extension_interference",
    COMPROMISED_ENVIRONMENT = "compromised_environment",
    WEAK_RANDOM = "weak_random",
    PROTOTYPE_POLLUTION = "prototype_pollution",
    FUNCTION_HIJACKING = "function_hijacking",
    INSECURE_CONTEXT = "insecure_context",
    BROWSER_EXTENSION = "browser_extension",
    IFRAME_EMBEDDING = "iframe_embedding",
    DEVTOOLS_OPEN = "devtools_open"
}
/**
 * Security check
 */
interface SecurityCheck {
    /**
     * Check name
     */
    name: string;
    /**
     * Check description
     */
    description: string;
    /**
     * Whether the check passed
     */
    passed: boolean;
    /**
     * Check result details
     */
    details?: any;
}
/**
 * Security verification options
 */
interface SecurityVerificationOptions {
    /**
     * Whether to check for debuggers
     * @default true
     */
    checkDebugger?: boolean;
    /**
     * Whether to check for extension interference
     * @default true
     */
    checkExtensions?: boolean;
    /**
     * Whether to check for compromised environment
     * @default true
     */
    checkEnvironment?: boolean;
    /**
     * Whether to check for weak random number generation
     * @default true
     */
    checkRandom?: boolean;
    /**
     * Whether to check for prototype pollution
     * @default true
     */
    checkPrototypePollution?: boolean;
    /**
     * Whether to check for function hijacking
     * @default true
     */
    checkFunctionHijacking?: boolean;
    /**
     * Whether to check for secure context
     * @default true
     */
    checkSecureContext?: boolean;
    /**
     * Whether to check for iframe embedding
     * @default true
     */
    checkIframeEmbedding?: boolean;
    /**
     * Whether to check for open DevTools
     * @default true
     */
    checkDevTools?: boolean;
    /**
     * Custom checks to run
     */
    customChecks?: Array<() => SecurityCheck>;
}
/**
 * Verifies the security of the runtime environment
 *
 * @param options - Verification options
 * @returns Verification result
 */
declare function verifyRuntimeSecurity(options?: SecurityVerificationOptions): SecurityVerificationResult;

/**
 * Secure Serialization Module
 *
 * This module provides secure methods for serializing and deserializing data,
 * protecting against prototype pollution, object injection, and other
 * serialization-related vulnerabilities.
 */
/**
 * Serialization options
 */
interface SerializationOptions {
    /**
     * Whether to sign the serialized data
     * @default true
     */
    sign?: boolean;
    /**
     * Secret key for signing
     * If not provided, a random key will be generated
     */
    signKey?: string;
    /**
     * Whether to encrypt the serialized data
     * @default false
     */
    encrypt?: boolean;
    /**
     * Encryption key
     * Required if encrypt is true
     */
    encryptKey?: string;
    /**
     * Whether to include a timestamp
     * @default true
     */
    includeTimestamp?: boolean;
    /**
     * Whether to include a nonce
     * @default true
     */
    includeNonce?: boolean;
    /**
     * Whether to validate object types during deserialization
     * @default true
     */
    validateTypes?: boolean;
    /**
     * Allowed classes for deserialization
     * If provided, only these classes will be instantiated during deserialization
     */
    allowedClasses?: string[];
}
/**
 * Deserialization options
 */
interface DeserializationOptions {
    /**
     * Whether to verify the signature
     * @default true
     */
    verifySignature?: boolean;
    /**
     * Secret key for signature verification
     * Required if verifySignature is true
     */
    signKey?: string;
    /**
     * Whether to decrypt the data
     * @default false
     */
    decrypt?: boolean;
    /**
     * Decryption key
     * Required if decrypt is true
     */
    decryptKey?: string;
    /**
     * Whether to validate the timestamp
     * @default true
     */
    validateTimestamp?: boolean;
    /**
     * Maximum age of the data in milliseconds
     * @default 3600000 (1 hour)
     */
    maxAge?: number;
    /**
     * Whether to validate object types during deserialization
     * @default true
     */
    validateTypes?: boolean;
    /**
     * Allowed classes for deserialization
     * If provided, only these classes will be instantiated during deserialization
     */
    allowedClasses?: string[];
}
/**
 * Serialization result
 */
interface SerializationResult {
    /**
     * Serialized data
     */
    data: string;
    /**
     * Signature of the data
     */
    signature?: string;
    /**
     * Timestamp when the data was serialized
     */
    timestamp?: number;
    /**
     * Nonce used for encryption
     */
    nonce?: string;
}
/**
 * Deserialization result
 */
interface DeserializationResult<T> {
    /**
     * Deserialized data
     */
    data: T;
    /**
     * Whether the signature is valid
     */
    validSignature?: boolean;
    /**
     * Whether the timestamp is valid
     */
    validTimestamp?: boolean;
    /**
     * Timestamp when the data was serialized
     */
    timestamp?: number;
    /**
     * Age of the data in milliseconds
     */
    age?: number;
}
/**
 * Securely serializes data
 *
 * @param data - Data to serialize
 * @param options - Serialization options
 * @returns Serialization result
 */
declare function secureSerialize<T>(data: T, options?: SerializationOptions): SerializationResult;
/**
 * Securely deserializes data
 *
 * @param serialized - Serialized data
 * @param options - Deserialization options
 * @returns Deserialization result
 */
declare function secureDeserialize<T>(serialized: SerializationResult, options?: DeserializationOptions): DeserializationResult<T>;

/**
 * XyPrissSecurity - Fortified Function Core Types
 * Modular type definitions for the fortified function system
 */

interface FortifiedFunctionOptions {
    ultraFast?: boolean | "minimal" | "standard" | "maximum" | undefined;
    autoEncrypt?: boolean;
    secureParameters?: (string | number)[];
    parameterValidation?: boolean;
    memoryWipeDelay?: number;
    stackTraceProtection?: boolean;
    smartSecurity?: boolean;
    threatDetection?: boolean;
    memoize?: boolean;
    /**
     * Timeout in milliseconds. Default is 14 seconds.
     */
    timeout?: number;
    retries?: number;
    maxRetryDelay?: number;
    smartCaching?: boolean;
    cacheStrategy?: "lru" | "lfu" | "adaptive";
    cacheTTL?: number;
    maxCacheSize?: number;
    errorHandling?: "graceful";
    precompile?: boolean;
    optimizeExecution?: boolean;
    enableJIT?: boolean;
    enableSIMD?: boolean;
    enableWebAssembly?: boolean;
    memoryOptimization?: "none" | "standard" | "aggressive";
    enableVectorization?: boolean;
    enableParallelExecution?: boolean;
    enableZeroCopy?: boolean;
    enableNativeOptimizations?: boolean;
    jitThreshold?: number;
    simdThreshold?: number;
    autoTuning?: boolean;
    predictiveAnalytics?: boolean;
    adaptiveTimeout?: boolean;
    intelligentRetry?: boolean;
    anomalyDetection?: boolean;
    performanceRegression?: boolean;
    auditLog?: boolean;
    performanceTracking?: boolean;
    debugMode?: boolean;
    detailedMetrics?: boolean;
    memoryPool?: boolean;
    maxMemoryUsage?: number;
    autoCleanup?: boolean;
    smartMemoryManagement?: boolean;
    memoryPressureHandling?: boolean;
}
interface FunctionStats {
    executionCount: number;
    totalExecutionTime: number;
    averageExecutionTime: number;
    memoryUsage: number;
    cacheHits: number;
    cacheMisses: number;
    errorCount: number;
    lastExecuted: Date;
    securityEvents: number;
    timingStats?: TimingStats;
}
interface TimingMeasurement {
    label: string;
    startTime: number;
    endTime?: number;
    duration?: number;
    metadata?: Record<string, any>;
}
interface TimingStats {
    totalMeasurements: number;
    completedMeasurements: number;
    activeMeasurements: number;
    measurements: TimingMeasurement[];
    summary: {
        totalDuration: number;
        averageDuration: number;
        minDuration: number;
        maxDuration: number;
        slowestOperation: string;
        fastestOperation: string;
    };
}
interface AuditEntry {
    timestamp: Date;
    executionId: string;
    parametersHash: string;
    executionTime: number;
    memoryUsage: number;
    success: boolean;
    errorMessage?: string;
    securityFlags: string[];
}
interface SecureExecutionContext {
    executionId: string;
    encryptedParameters: Map<string, string>;
    secureBuffers: Map<string, SecureBuffer>;
    startTime: number;
    memorySnapshot: number;
    auditEntry: AuditEntry;
}
interface ExecutionEvent {
    executionId: string;
    timestamp: Date;
    type: "start" | "success" | "error" | "timeout" | "retry";
    data?: any;
}
interface CacheEntry<R> {
    result: R;
    timestamp: number;
    accessCount: number;
    lastAccessed: Date;
    ttl?: number;
    priority?: number;
    size?: number;
    frequency?: number;
}
interface SecurityFlags {
    encrypted: boolean;
    audited: boolean;
    memoryManaged: boolean;
    stackProtected: boolean;
}
interface PerformanceMetrics {
    executionTime: number;
    memoryUsage: number;
    cpuUsage: number;
    cacheHitRate: number;
    errorRate: number;
    throughput: number;
    latency: number;
}
interface ExecutionPattern {
    parametersHash: string;
    frequency: number;
    averageExecutionTime: number;
    lastExecuted: Date;
    predictedNextExecution?: Date;
    cacheWorthiness: number;
}
interface OptimizationSuggestion {
    type: "cache" | "timeout" | "retry" | "memory" | "security";
    priority: "low" | "medium" | "high" | "critical";
    description: string;
    expectedImprovement: number;
    implementation: string;
}
interface AnalyticsData {
    patterns: ExecutionPattern[];
    trends: PerformanceMetrics[];
    anomalies: AnomalyDetection[];
    predictions: PredictiveAnalysis[];
}
interface AnomalyDetection {
    type: "performance" | "memory" | "security" | "error";
    severity: "low" | "medium" | "high";
    description: string;
    timestamp: Date;
    metrics: Record<string, number>;
}
interface PredictiveAnalysis {
    metric: string;
    currentValue: number;
    predictedValue: number;
    confidence: number;
    timeframe: number;
    trend: "increasing" | "decreasing" | "stable";
}
/**
 * Enhanced function type that provides access to FortifiedFunction methods
 * while maintaining the original function signature
 */
interface EnhancedFortifiedFunction<T extends any[], R> {
    (...args: T): R;
    getStats(): any;
    getAnalyticsData(): any;
    getOptimizationSuggestions(): any[];
    getPerformanceTrends(): any;
    detectAnomalies(): any[];
    getDetailedMetrics(): any;
    clearCache(): void;
    getCacheStats(): {
        hits: number;
        misses: number;
        size: number;
    };
    warmCache(args: T[]): Promise<void>;
    handleMemoryPressure(level: "low" | "medium" | "high"): void;
    optimizePerformance(): void;
    updateOptions(newOptions: Partial<FortifiedFunctionOptions>): void;
    getConfiguration(): Partial<FortifiedFunctionOptions>;
    startTimer(label: string, metadata?: Record<string, any>): void;
    endTimer(label: string, additionalMetadata?: Record<string, any>): void;
    measureDelay(startPoint: string, endPoint: string): number;
    timeFunction<U>(label: string, fn: () => U | Promise<U>, metadata?: Record<string, any>): Promise<U>;
    getTimingStats(): any;
    clearTimings(): void;
    _fortified: any;
}

/**
 * XyPrissSecurity - Optimized Fortified Function Core (Minimal Architecture)
 * High-performance implementation with singleton pattern
 * Migrated from complex implementation to maintain architecture
 */

/**
 * Optimized Fortified Function - High-performance implementation
 * Uses singleton pattern for optimal resource utilization
 */
declare class FortifiedFunctionCore<T extends any[], R> extends EventEmitter {
    private static instances;
    private static globalMetrics;
    private readonly functionId;
    private readonly originalFunction;
    private readonly options;
    private readonly securityManager;
    private readonly executionContextManager;
    private readonly cacheManager;
    private readonly statsManager;
    private readonly memoryManager;
    private readonly executionEngine;
    private readonly executionRouter;
    private readonly timingManager;
    private readonly apiManager;
    private readonly securityHandler;
    private readonly performanceMonitor;
    private readonly funcExecutionEngine;
    private isDestroyed;
    private cleanupInterval?;
    private readonly ultraFastEngine;
    private readonly ultraFastCache;
    private readonly ultraFastAllocator;
    private readonly functionSignature;
    private executionCount;
    private lastOptimizationCheck;
    private readonly optimizationCheckInterval;
    private constructor();
    private generateFunctionId;
    /**
     * Generate function signature for optimization
     */
    private generateFunctionSignature;
    /**
     * Setup automatic cleanup
     */
    private setupAutoCleanup;
    /**
     * Factory method with singleton pattern for optimal resource usage
     */
    static create<T extends any[], R>(fn: (...args: T) => R | Promise<R>, options?: Partial<FortifiedFunctionOptions>, functionId?: string): FortifiedFunctionCore<T, R>;
    /**
     * Get existing instance by ID
     */
    static getInstance<T extends any[], R>(functionId: string): FortifiedFunctionCore<T, R> | null;
    /**
     * Get all active instances
     */
    static getAllInstances(): FortifiedFunctionCore<any, any>[];
    /**
     * Get global performance metrics
     */
    static getGlobalMetrics(): {
        totalInstances: number;
        totalExecutions: number;
        totalCacheHits: number;
        totalCacheMisses: number;
        averageExecutionTime: number;
    };
    /**
     * Generate unique function ID
     */
    private static generateFunctionId;
    /**
     * Get function ID
     */
    getFunctionId(): string;
    /**
     * Get current configuration
     */
    getConfiguration(): Required<FortifiedFunctionOptions>;
    /**
     * Execute with extreme performance optimizations
     */
    execute(...args: T): Promise<R>;
    /**
     * Execute with ultra-fast engine (delegated to ExecutionRouter)
     */
    private executeWithUltraFastEngine;
    /**
     * Ultra-fast execution (delegated to ExecutionRouter)
     */
    private executeUltraFast;
    /**
     * Standard execution with full security and monitoring (using existing components)
     */
    private executeStandard;
    /**
     * Perform optimization check (delegated to ApiManager)
     */
    private performOptimizationCheck;
    getStats(): FunctionStats;
    getAuditLog(): AuditEntry[];
    getCacheStats(): {
        totalHits: number;
        totalMisses: number;
        hitRate: number;
        hitRatePercentage: number;
        size: number;
        maxSize: number;
        utilizationRate: number;
        strategy: "lru" | "lfu" | "adaptive";
        averageAccessCount: number;
        memoryUsage: number;
        memoryUsageMB: number;
        averageEntrySize: number;
        topFrequentKeys: {
            key: string;
            frequency: number;
        }[];
        recentEvictions: number;
        adaptationHistory: number;
        hits: number;
        misses: number;
        evictions: number;
        totalSize: number;
        compressionRatio: number;
        adaptations: number;
        memoryPressureEvents: number;
    };
    getAnalyticsData(): AnalyticsData;
    getOptimizationSuggestions(): OptimizationSuggestion[];
    getPerformanceTrends(): PerformanceMetrics[];
    detectAnomalies(): AnomalyDetection[];
    clearCache(): void;
    warmCache(): void;
    handleMemoryPressure(level: "low" | "medium" | "high"): void;
    /**
     * Set up event forwarding from components
     */
    private setupEventForwarding;
    /**
     * Auto-apply optimizations (delegated to ApiManager)
     */
    private autoApplyOptimizations;
    /**
     * Get detailed metrics (delegated to components)
     */
    getDetailedMetrics(): {
        stats: FunctionStats;
        cacheStats: {
            totalHits: number;
            totalMisses: number;
            hitRate: number;
            hitRatePercentage: number;
            size: number;
            maxSize: number;
            utilizationRate: number;
            strategy: "lru" | "lfu" | "adaptive";
            averageAccessCount: number;
            memoryUsage: number;
            memoryUsageMB: number;
            averageEntrySize: number;
            topFrequentKeys: {
                key: string;
                frequency: number;
            }[];
            recentEvictions: number;
            adaptationHistory: number;
            hits: number;
            misses: number;
            evictions: number;
            totalSize: number;
            compressionRatio: number;
            adaptations: number;
            memoryPressureEvents: number;
        };
        analytics: AnalyticsData;
        suggestions: OptimizationSuggestion[];
        trends: PerformanceMetrics[];
        anomalies: AnomalyDetection[];
        functionId: string;
        globalMetrics: {
            totalInstances: number;
            totalExecutions: number;
            totalCacheHits: number;
            totalCacheMisses: number;
            averageExecutionTime: number;
        };
    } | null;
    /**
     * Update function options dynamically
     */
    updateOptions(newOptions: Partial<FortifiedFunctionOptions>): void;
    /**
     * Performance timing methods (delegated to TimingManager)
     */
    startTimer(label: string, metadata?: Record<string, any>): void;
    endTimer(label: string, additionalMetadata?: Record<string, any>): number;
    measureDelay(startPoint: string, endPoint: string): number;
    timeFunction<U>(label: string, fn: () => U | Promise<U>, metadata?: Record<string, any>): Promise<{
        result: U;
        duration: number;
    }>;
    getTimingStats(): TimingStats;
    clearTimings(): void;
    getMeasurementsByPattern(pattern: RegExp): any[];
    isTimerActive(label: string): boolean;
    getActiveTimers(): string[];
    clearAuditLog(): void;
    getActiveExecutionsCount(): number;
    getUltraFastMetrics(): any;
    optimizePerformance(): void;
    /**
     * Enhanced destroy method with comprehensive cleanup
     */
    destroy(): void;
    /**
     * Destroy all instances (cleanup utility)
     */
    static destroyAll(): void;
    /**
     * Get instance count
     */
    static get instancesSize(): number;
}

/**
 * Legacy Fortified Function - Backward compatibility wrapper
 * Delegates to the optimized modular system while maintaining the same API
 */
declare class FortifiedFunction<T extends any[], R> extends EventEmitter {
    private readonly optimizedInstance;
    constructor(fn: (...args: T) => R | Promise<R>, options?: FortifiedFunctionOptions);
    /**
     * Execute the function with all optimizations
     */
    execute(...args: T): Promise<R>;
    /**
     * Get function statistics
     */
    getStats(): FunctionStats;
    /**
     * Get audit log
     */
    getAuditLog(): AuditEntry[];
    /**
     * Get cache statistics
     */
    getCacheStats(): {
        totalHits: number;
        totalMisses: number;
        hitRate: number;
        hitRatePercentage: number;
        size: number;
        maxSize: number;
        utilizationRate: number;
        strategy: "lru" | "lfu" | "adaptive";
        averageAccessCount: number;
        memoryUsage: number;
        memoryUsageMB: number;
        averageEntrySize: number;
        topFrequentKeys: {
            key: string;
            frequency: number;
        }[];
        recentEvictions: number;
        adaptationHistory: number;
        hits: number;
        misses: number;
        evictions: number;
        totalSize: number;
        compressionRatio: number;
        adaptations: number;
        memoryPressureEvents: number;
    };
    /**
     * Clear cache
     */
    clearCache(): void;
    /**
     * Clear audit log
     */
    clearAuditLog(): void;
    /**
     * Get active executions count
     */
    getActiveExecutionsCount(): number;
    /**
     * Get analytics data
     */
    getAnalyticsData(): AnalyticsData;
    /**
     * Get optimization suggestions
     */
    getOptimizationSuggestions(): OptimizationSuggestion[];
    /**
     * Get performance trends
     */
    getPerformanceTrends(): PerformanceMetrics[];
    /**
     * Warm cache
     */
    warmCache(): void;
    /**
     * Handle memory pressure
     */
    handleMemoryPressure(level: "low" | "medium" | "high"): void;
    /**
     * Detect anomalies
     */
    detectAnomalies(): AnomalyDetection[];
    /**
     * Get detailed metrics
     */
    getDetailedMetrics(): {
        stats: FunctionStats;
        cacheStats: {
            totalHits: number;
            totalMisses: number;
            hitRate: number;
            hitRatePercentage: number;
            size: number;
            maxSize: number;
            utilizationRate: number;
            strategy: "lru" | "lfu" | "adaptive";
            averageAccessCount: number;
            memoryUsage: number;
            memoryUsageMB: number;
            averageEntrySize: number;
            topFrequentKeys: {
                key: string;
                frequency: number;
            }[];
            recentEvictions: number;
            adaptationHistory: number;
            hits: number;
            misses: number;
            evictions: number;
            totalSize: number;
            compressionRatio: number;
            adaptations: number;
            memoryPressureEvents: number;
        };
        analytics: AnalyticsData;
        suggestions: OptimizationSuggestion[];
        trends: PerformanceMetrics[];
        anomalies: AnomalyDetection[];
        functionId: string;
        globalMetrics: {
            totalInstances: number;
            totalExecutions: number;
            totalCacheHits: number;
            totalCacheMisses: number;
            averageExecutionTime: number;
        };
    } | null;
    /**
     * Get ultra-fast component metrics
     */
    getUltraFastMetrics(): any;
    /**
     * Update function options dynamically
     */
    updateOptions(newOptions: Partial<FortifiedFunctionOptions>): void;
    /**
     * Optimize performance by applying recommended settings
     */
    optimizePerformance(): void;
    /**
     * Start timing a specific operation
     */
    startTimer(label: string, metadata?: Record<string, any>): void;
    /**
     * End timing for a specific operation
     */
    endTimer(label: string, additionalMetadata?: Record<string, any>): number;
    /**
     * Measure delay between two points
     */
    measureDelay(startPoint: string, endPoint: string): number;
    /**
     * Time a function execution
     */
    timeFunction<U>(label: string, fn: () => U | Promise<U>, metadata?: Record<string, any>): Promise<{
        result: U;
        duration: number;
    }>;
    /**
     * Get timing statistics
     */
    getTimingStats(): TimingStats;
    /**
     * Clear all timing measurements
     */
    clearTimings(): void;
    /**
     * Get measurements by pattern
     */
    getMeasurementsByPattern(pattern: RegExp): any[];
    /**
     * Check if a timer is active
     */
    isTimerActive(label: string): boolean;
    /**
     * Get active timers
     */
    getActiveTimers(): string[];
    /**
     * Destroy and clean up all resources
     */
    destroy(): void;
}

/***************************************************************************
 * XyPrissSecurity - Secure Array Types
 *
 * This file contains type definitions for the SecureArrayarchitecture
 *
 * @author Nehonix
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */
/**
 * XyPrissSecurity - Fortified Functions (Modular Architecture)
 * Main entry point for the fortified function system
 */

/**
 * Zero-Configuration Smart Function Factory - EXTREME PERFORMANCE EDITION
 *
 * Creates ultra-fast fortified functions with enterprise-grade security,
 * extreme performance optimization, and intelligent caching enabled by default.
 * Optimized for sub-millisecond execution times while maintaining security.
 *
 * @param fn - The function to be fortified with extreme performance capabilities
 * @param options - Optional configuration overrides (performance-first defaults)
 * @returns A fortified function with extreme performance and security features
 *
 * @example
 * ```typescript
 * import { func } from 'xypriss-security';
 *
 * // Zero configuration needed - extreme performance enabled by default
 * const ultraFastFunction = func(async (data: string) => {
 *     return processData(data);
 * });
 *
 * // Execute with sub-millisecond performance
 * const result = await ultraFastFunction('sensitive data');
 *
 * // Optional: Override specific settings if needed
 * const customFunction = func(myFunction, {
 *     ultraFast: "maximum",
 *     maxCacheSize: 10000,
 *     enableJIT: true
 * });
 *
 *
 * const syncFn = func((x: number) => x * 2); // Returns number
 * syncFn(5).toFixed(2); // Type inference works!

 * const asyncFn = func(async (x: number) => x * 2); // Returns Promise<number>
 * asyncFn(5).then((result) => result.toFixed(2)); // Type inference works!
 *
 * ```
 */
declare function func<T extends any[], F extends (...args: T) => any>(fn: F, options?: Partial<FortifiedFunctionOptions>): EnhancedFortifiedFunction<T, ReturnType<F>>;
/**
 * Create a fortified function with full access to smart analytics and optimization
 * Provides complete access to performance metrics, analytics, and optimization features
 *
 * @example
 * ```typescript
 * import { createFortifiedFunction } from 'xypriss-security';
 *
 * const fortified = createFortifiedFunction(myFunction, {
 *     autoEncrypt: true,
 *     smartCaching: true,
 *     predictiveAnalytics: true,
 *     detailedMetrics: true
 * });
 *
 * // Execute
 * const result = await fortified.execute('data');
 *
 * // Access enhanced analytics
 * const analytics = fortified.getAnalyticsData();
 * const suggestions = fortified.getOptimizationSuggestions();
 * const trends = fortified.getPerformanceTrends();
 * const anomalies = fortified.detectAnomalies();
 *
 * // Smart actions
 * fortified.warmCache();
 * fortified.handleMemoryPressure('medium');
 *
 * // Get comprehensive metrics
 * const detailedMetrics = fortified.getDetailedMetrics();
 *
 * // Clean up when done
 * fortified.destroy();
 * ```
 */
declare function createFortifiedFunction<T extends any[], R>(fn: (...args: T) => R | Promise<R>, options?: Partial<FortifiedFunctionOptions>): FortifiedFunctionCore<T, R>;

/**
 * @author iDevo
 * Enhanced RSA Key Size Calculator
 * Calculates appropriate RSA key size based on data size with improved security and performance
 */
declare const HASH_SIZES: {
    readonly sha1: 20;
    readonly sha224: 28;
    readonly sha256: 32;
    readonly sha384: 48;
    readonly sha512: 64;
    readonly sha3_256: 32;
    readonly sha3_384: 48;
    readonly sha3_512: 64;
};
declare const SECURITY_LEVELS: {
    readonly minimal: {
        readonly bits: 80;
        readonly description: "Legacy compatibility only";
        readonly minKeySize: 1024;
    };
    readonly standard: {
        readonly bits: 112;
        readonly description: "Current standard security";
        readonly minKeySize: 2048;
    };
    readonly high: {
        readonly bits: 128;
        readonly description: "High security applications";
        readonly minKeySize: 3072;
    };
    readonly maximum: {
        readonly bits: 256;
        readonly description: "Maximum security";
        readonly minKeySize: 15360;
    };
};
type HashAlgorithm = keyof typeof HASH_SIZES;
type SecurityLevel = keyof typeof SECURITY_LEVELS;
interface RSAKeyPair {
    publicKey: string;
    privateKey: string;
    keySize: number;
    maxDataSize: number;
    hashAlgorithm: HashAlgorithm;
}
interface RSATestResult {
    success: boolean;
    error?: string;
    encryptedSize?: number;
    decryptedMatches?: boolean;
    performanceMs?: number;
}
interface RSARecommendation {
    keySize: number;
    maxDataSize: number;
    securityLevel: "minimal" | "standard" | "high" | "maximum";
    recommendation: string;
}
interface KeyValidationResult {
    isValid: boolean;
    errors: string[];
    warnings: string[];
    securityScore: number;
    recommendations: string[];
}
/**
 * Calculate the minimum RSA key size needed for the given data size
 * @param dataSize - Size of data to encrypt in bytes
 * @param hashAlgorithm - Hash algorithm for OAEP padding (default: sha256)
 * @param allowCustomSize - Allow non-standard key sizes (default: false)
 * @returns Recommended RSA key size in bits
 */
declare function calculateRSAKeySize(dataSize: number, hashAlgorithm?: HashAlgorithm, allowCustomSize?: boolean): number;
/**
 * Generate RSA key pair with appropriate size for the given data
 * @param dataSize - Size of data to encrypt in bytes
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @param allowCustomSize - Allow non-standard key sizes
 * @returns RSA key pair with metadata
 */
declare function generateRSAKeyPairForData(dataSize: number, hashAlgorithm?: HashAlgorithm, allowCustomSize?: boolean): RSAKeyPair;
/**
 * Generate password-protected RSA key pair
 * @param dataSize - Size of data to encrypt in bytes
 * @param passphrase - Password to protect the private key
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @returns Protected RSA key pair
 */
declare function generateProtectedRSAKeyPairForData(dataSize: number, passphrase: string, hashAlgorithm?: HashAlgorithm): RSAKeyPair;
/**
 * Get maximum data size that can be encrypted with a given RSA key size
 * @param rsaKeySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm used for OAEP
 * @returns Maximum data size in bytes
 */
declare function getMaxDataSizeForRSAKey(rsaKeySize: number, hashAlgorithm?: HashAlgorithm): number;
/**
 * Validate if data can be encrypted with the given RSA key
 * @param dataSize - Size of data in bytes
 * @param rsaKeySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm used for OAEP
 * @returns Validation result with details
 */
declare function validateDataSizeForRSAKey(dataSize: number, rsaKeySize: number, hashAlgorithm?: HashAlgorithm): {
    valid: boolean;
    maxDataSize: number;
    recommendation?: string;
};
/**
 * Get RSA key size recommendations for different security levels
 * @param dataSize - Size of data to encrypt in bytes
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @returns Array of recommendations
 */
declare function getRSARecommendations(dataSize: number, hashAlgorithm?: HashAlgorithm): RSARecommendation[];
/**
 * Test RSA encryption/decryption with performance monitoring
 * @param dataSize - Size of test data in bytes
 * @param rsaKeySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm for OAEP padding
 * @param iterations - Number of test iterations for performance measurement
 * @returns Comprehensive test result
 */
declare function testRSAWithDataSize(dataSize: number, rsaKeySize: number, hashAlgorithm?: HashAlgorithm, iterations?: number): Promise<RSATestResult>;
/**
 * Benchmark RSA performance across different key sizes
 * @param dataSize - Size of test data in bytes
 * @param keySizes - Array of key sizes to test
 * @param iterations - Number of iterations per key size
 * @returns Performance comparison results
 */
declare function benchmarkRSAPerformance(dataSize: number, keySizes?: number[], iterations?: number): Promise<Array<{
    keySize: number;
    avgTimeMs: number;
    success: boolean;
    error?: string;
}>>;
/**
 * Utility to suggest hybrid encryption when RSA alone is inefficient
 * @param dataSize - Size of data to encrypt in bytes
 * @returns Suggestion for encryption approach
 */
declare function getEncryptionSuggestion(dataSize: number): {
    approach: "rsa" | "hybrid";
    reason: string;
    details?: {
        aesKeySize: number;
        rsaKeySize: number;
        estimatedPerformanceGain?: string;
    };
};
/**
 * Enhanced key validation with security assessment
 * @param publicKey - RSA public key in PEM format
 * @param privateKey - RSA private key in PEM format (optional)
 * @returns Comprehensive validation result
 */
declare function validateRSAKeyPair(publicKey: string, privateKey?: string): KeyValidationResult;
/**
 * Enhanced security assessment for RSA configuration
 * @param keySize - RSA key size in bits
 * @param hashAlgorithm - Hash algorithm used
 * @param dataSize - Size of data to encrypt
 * @returns Security assessment with recommendations
 */
declare function assessRSASecurity(keySize: number, hashAlgorithm: HashAlgorithm, dataSize: number): {
    level: SecurityLevel;
    score: number;
    vulnerabilities: string[];
    recommendations: string[];
    compliance: {
        nist: boolean;
        fips: boolean;
        commonCriteria: boolean;
    };
};

/**
 * Enhanced encoding utilities for various formats
 */
/**
 * Convert a buffer to a hexadecimal string
 * @param buffer - The buffer to convert
 * @param uppercase - Whether to use uppercase letters (default: false)
 * @param separator - Optional separator between bytes (e.g., ':', ' ', '-')
 * @returns Hexadecimal string representation
 */
declare function bufferToHex(buffer: Uint8Array, uppercase?: boolean, separator?: string): string;
/**
 * Convert a hexadecimal string to a buffer
 * @param hex - The hexadecimal string to convert
 * @returns Uint8Array representation
 */
declare function hexToBuffer(hex: string): Uint8Array;
/**
 * Convert a buffer to a binary string
 * @param buffer - The buffer to convert
 * @param separator - Optional separator between bytes (e.g., ' ', '-')
 * @returns Binary string representation
 */
declare function bufferToBinary(buffer: Uint8Array, separator?: string): string;
/**
 * Convert a binary string to a buffer
 * @param binary - The binary string to convert
 * @returns Uint8Array representation
 */
declare function binaryToBuffer(binary: string): Uint8Array;
/**
 * Convert a number to binary string with specified bit width
 * @param num - The number to convert
 * @param bits - The number of bits (default: 8)
 * @returns Binary string representation
 */
declare function numberToBinary(num: number, bits?: number): string;
/**
 * Convert a binary string to a number
 * @param binary - The binary string to convert
 * @returns Number representation
 */
declare function binaryToNumber(binary: string): number;
/**
 * Convert a buffer to a Base64 string
 * @param buffer - The buffer to convert
 * @param urlSafe - Whether to use URL-safe Base64 (default: false)
 * @returns Base64 string representation
 */
declare function bufferToBase64(buffer: Uint8Array, urlSafe?: boolean): string;
/**
 * Convert a Base64 string to a buffer
 * @param base64 - The Base64 string to convert
 * @param urlSafe - Whether the input is URL-safe Base64 (default: false)
 * @returns Uint8Array representation
 */
declare function base64ToBuffer(base64: string, urlSafe?: boolean): Uint8Array;
/**
 * Convert a buffer to a Base58 string (Bitcoin style)
 * @param buffer - The buffer to convert
 * @returns Base58 string representation
 */
declare function bufferToBase58(buffer: Uint8Array): string;
/**
 * Convert a Base58 string to a buffer
 * @param base58 - The Base58 string to convert
 * @returns Uint8Array representation
 */
declare function base58ToBuffer(base58: string): Uint8Array;
/**
 * Convert a buffer to a Base32 string (RFC 4648)
 * @param buffer - The buffer to convert
 * @param padding - Whether to include padding (default: true)
 * @returns Base32 string representation
 */
declare function bufferToBase32(buffer: Uint8Array, padding?: boolean): string;
/**
 * Convert a Base32 string to a buffer
 * @param base32 - The Base32 string to convert
 * @returns Uint8Array representation
 */
declare function base32ToBuffer(base32: string): Uint8Array;
/**
 * Convert a buffer to an octal string
 * @param buffer - The buffer to convert
 * @param separator - Optional separator between bytes
 * @returns Octal string representation
 */
declare function bufferToOctal(buffer: Uint8Array, separator?: string): string;
/**
 * Convert an octal string to a buffer
 * @param octal - The octal string to convert
 * @returns Uint8Array representation
 */
declare function octalToBuffer(octal: string): Uint8Array;
/**
 * Convert a number to octal string
 * @param num - The number to convert
 * @returns Octal string representation
 */
declare function numberToOctal(num: number): string;
/**
 * Convert an octal string to a number
 * @param octal - The octal string to convert
 * @returns Number representation
 */
declare function octalToNumber(octal: string): number;
/**
 * Convert a string to a buffer using UTF-8 encoding
 * @param str - The string to convert
 * @returns Uint8Array representation
 */
declare function stringToBuffer(str: string): Uint8Array;
/**
 * Convert a string directly to hexadecimal representation
 * @param str - The string to convert
 * @param uppercase - Whether to use uppercase letters (default: false)
 * @param separator - Optional separator between bytes
 * @returns Hexadecimal string representation
 */
declare function stringToHex(str: string, uppercase?: boolean, separator?: string): string;
/**
 * Convert a hexadecimal string back to a string
 * @param hex - The hexadecimal string to convert
 * @returns String representation
 */
declare function hexToString(hex: string): string;
/**
 * Convert a string directly to Base64 encoding
 * @param str - The string to encode
 * @param urlSafe - Whether to use URL-safe Base64 (default: false)
 * @returns Base64 encoded string
 */
declare function stringToBase64(str: string, urlSafe?: boolean): string;
/**
 * Convert a Base64 encoded string back to string
 * @param base64 - The Base64 encoded string
 * @param urlSafe - Whether the input is URL-safe Base64 (default: false)
 * @returns Decoded string
 */
declare function base64ToString(base64: string, urlSafe?: boolean): string;
/**
 * Convert a buffer to a string using UTF-8 decoding
 * @param buffer - The buffer to convert
 * @returns String representation
 */
declare function bufferToString(buffer: Uint8Array): string;
/**
 * Convert a string to ASCII bytes
 * @param str - The string to convert
 * @returns Uint8Array with ASCII codes
 */
declare function stringToAscii(str: string): Uint8Array;
/**
 * Convert ASCII bytes to a string
 * @param buffer - The buffer with ASCII codes
 * @returns String representation
 */
declare function asciiToString(buffer: Uint8Array): string;
/**
 * Convert a string to Base64URL encoding
 * @param str - The string to encode
 * @returns Base64URL encoded string
 */
declare function stringToBase64Url(str: string): string;
/**
 * Convert a Base64URL encoded string back to string
 * @param base64url - The Base64URL encoded string
 * @returns Decoded string
 */
declare function base64UrlToString(base64url: string): string;
/**
 * Convert regular Base64 to Base64URL
 * @param base64 - The regular Base64 string
 * @returns Base64URL string
 */
declare function base64ToBase64Url(base64: string): string;
/**
 * Convert Base64URL to regular Base64
 * @param base64url - The Base64URL string
 * @returns Regular Base64 string
 */
declare function base64UrlToBase64(base64url: string): string;
/**
 * Convert a buffer to Base64URL encoding
 * @param buffer - The buffer to convert
 * @returns Base64URL encoded string
 */
declare function bufferToBase64Url(buffer: Uint8Array): string;
/**
 * Convert a Base64URL string to a buffer
 * @param base64url - The Base64URL string to convert
 * @returns Uint8Array representation
 */
declare function base64UrlToBuffer(base64url: string): Uint8Array;
/**
 * URL encode a string
 * @param str - The string to encode
 * @returns URL encoded string
 */
declare function urlEncode(str: string): string;
/**
 * URL decode a string
 * @param str - The URL encoded string to decode
 * @returns Decoded string
 */
declare function urlDecode(str: string): string;
/**
 * Convert a buffer to URL encoded string
 * @param buffer - The buffer to convert
 * @returns URL encoded string
 */
declare function bufferToUrlEncoded(buffer: Uint8Array): string;
/**
 * Convert a number to any base (2-36)
 * @param num - The number to convert
 * @param base - The target base (2-36)
 * @returns String representation in the specified base
 */
declare function numberToBase(num: number, base: number): string;
/**
 * Convert a string from any base (2-36) to a number
 * @param str - The string to convert
 * @param base - The base of the input string (2-36)
 * @returns Number representation
 */
declare function baseToNumber(str: string, base: number): number;
/**
 * Convert between different number bases
 * @param str - The input string
 * @param fromBase - The base of the input string
 * @param toBase - The target base
 * @returns String representation in the target base
 */
declare function convertBase(str: string, fromBase: number, toBase: number): string;
/**
 * Convert a 16-bit number to bytes (little-endian)
 * @param num - The 16-bit number
 * @returns Uint8Array with 2 bytes
 */
declare function uint16ToBytes(num: number): Uint8Array;
/**
 * Convert bytes to a 16-bit number (little-endian)
 * @param buffer - The buffer with 2 bytes
 * @returns 16-bit number
 */
declare function bytesToUint16(buffer: Uint8Array): number;
/**
 * Convert a 32-bit number to bytes (little-endian)
 * @param num - The 32-bit number
 * @returns Uint8Array with 4 bytes
 */
declare function uint32ToBytes(num: number): Uint8Array;
/**
 * Convert bytes to a 32-bit number (little-endian)
 * @param buffer - The buffer with 4 bytes
 * @returns 32-bit number
 */
declare function bytesToUint32(buffer: Uint8Array): number;
/**
 * Reverse byte order (swap endianness)
 * @param buffer - The buffer to reverse
 * @returns New buffer with reversed byte order
 */
declare function reverseBytes(buffer: Uint8Array): Uint8Array;
/**
 * Compare two buffers for equality
 * @param a - First buffer
 * @param b - Second buffer
 * @returns True if buffers are equal
 */
declare function buffersEqual(a: Uint8Array, b: Uint8Array): boolean;
/**
 * Concatenate multiple buffers
 * @param buffers - Array of buffers to concatenate
 * @returns New buffer containing all input buffers
 */
declare function concatBuffers(...buffers: Uint8Array[]): Uint8Array;
/**
 * XOR two buffers
 * @param a - First buffer
 * @param b - Second buffer
 * @returns New buffer with XOR result
 */
declare function xorBuffers(a: Uint8Array, b: Uint8Array): Uint8Array;
/**
 * Generate a random buffer
 * @param length - The length of the buffer
 * @returns Random buffer
 */
declare function randomBuffer(length: number): Uint8Array;
/**
 * Pad a buffer to a specific length
 * @param buffer - The buffer to pad
 * @param length - The target length
 * @param value - The padding value (default: 0)
 * @param left - Whether to pad on the left (default: false)
 * @returns Padded buffer
 */
declare function padBuffer(buffer: Uint8Array, length: number, value?: number, left?: boolean): Uint8Array;
/**
 * Calculate checksum of a buffer (simple XOR checksum)
 * @param buffer - The buffer to checksum
 * @returns Checksum value
 */
declare function simpleChecksum(buffer: Uint8Array): number;
/**
 * Split a buffer into chunks
 * @param buffer - The buffer to split
 * @param chunkSize - The size of each chunk
 * @returns Array of buffer chunks
 */
declare function chunkBuffer(buffer: Uint8Array, chunkSize: number): Uint8Array[];
/**
 * Format bytes as human-readable string
 * @param bytes - The number of bytes
 * @param decimals - Number of decimal places (default: 2)
 * @returns Formatted string (e.g., "1.23 KB")
 */
declare function formatBytes(bytes: number, decimals?: number): string;
/**
 * Auto-detect encoding format of a string
 * @param str - The string to analyze
 * @returns Detected format or 'unknown'
 */
declare function detectEncoding(str: string): string;

/**
 * Optimized XSS and SQL Injection Detection Patterns
 *
 * This module provides optimized regular expressions and patterns for detecting
 * various security vulnerabilities in user input. Designed for production use
 * with reduced false positives and improved performance.
 *
 * @author Seth Eleazar
 * @version 2.0.0
 * @since 1.0.0
 */
/**
 * SQL Injection Detection Patterns
 *
 * Optimized patterns for detecting SQL injection attempts with reduced false positives.
 * These patterns focus on high-confidence indicators while minimizing impact on
 * legitimate input containing SQL-like keywords.
 *
 * @type {RegExp[]}
 * @example
 * ```typescript
 * const userInput = "1' OR '1'='1";
 * const isSqlInjection = sqlPatterns.some(pattern => pattern.test(userInput));
 * ```
 */
declare const sqlPatterns: RegExp[];
/**
 * Cross-Site Scripting (XSS) Detection Patterns
 *
 * Optimized patterns for detecting XSS attempts with focus on executable content
 * and common bypass techniques. Reduced false positives for legitimate HTML/JavaScript.
 *
 * @type {RegExp[]}
 * @example
 * ```typescript
 * const userInput = "<script>alert('xss')</script>";
 * const isXSS = xssPatterns.some(pattern => pattern.test(userInput));
 * ```
 */
declare const xssPatterns: RegExp[];
/**
 * Context-specific injection patterns
 *
 * Patterns for detecting injection attacks in specific contexts like LDAP, XML, etc.
 * Each context has patterns tailored to the specific attack vectors.
 *
 * @type {Record<string, RegExp[]>}
 */
declare const contexts: Record<string, RegExp[]>;
/**
 * Common weak passwords list
 *
 * Curated list of commonly used passwords for validation.
 * Includes most frequent passwords from security breaches and common patterns.
 *
 * @type {string[]}
 * @readonly
 */
declare const commonPassword: readonly string[];
/**
 * Keyboard pattern detection expressions
 *
 * Patterns to detect common keyboard sequences and weak password patterns.
 * Useful for password strength validation.
 *
 * @type {RegExp[]}
 */
declare const keyboardPatterns: RegExp[];
/**
 * Validates input against SQL injection patterns
 *
 * @param input - The input string to validate
 * @returns True if potential SQL injection is detected
 * @example
 * ```typescript
 * if (detectSQLInjection(userInput)) {
 *   throw new Error('Potential SQL injection detected');
 * }
 * ```
 */
declare const detectSQLInjection: (input: string) => boolean;
/**
 * Validates input against XSS patterns
 *
 * @param input - The input string to validate
 * @returns True if potential XSS is detected
 * @example
 * ```typescript
 * if (detectXSS(userInput)) {
 *   // Sanitize or reject input
 * }
 * ```
 */
declare const detectXSS: (input: string) => boolean;
/**
 * Validates input against context-specific injection patterns
 *
 * @param input - The input string to validate
 * @param contextType - The context type to check against
 * @returns True if potential injection is detected for the given context
 * @example
 * ```typescript
 * if (detectContextInjection(ldapQuery, 'ldap')) {
 *   throw new Error('Potential LDAP injection detected');
 * }
 * ```
 */
declare const detectContextInjection: (input: string, contextType: keyof typeof contexts) => boolean;
/**
 * Checks if a password is in the common passwords list
 *
 * @param password - The password to check
 * @returns True if the password is commonly used
 * @example
 * ```typescript
 * if (isCommonPassword(userPassword)) {
 *   return { error: 'Please choose a stronger password' };
 * }
 * ```
 */
declare const isCommonPassword: (password: string) => boolean;
/**
 * Detects keyboard patterns in passwords
 *
 * @param password - The password to analyze
 * @returns True if keyboard patterns are detected
 * @example
 * ```typescript
 * if (hasKeyboardPattern(userPassword)) {
 *   // Suggest stronger password
 * }
 * ```
 */
declare const hasKeyboardPattern: (password: string) => boolean;

/**
 *  Function to test input against all patterns
 *  @example
 *  const testInput = "'; DROP TABLE users; --";
    const result = detectInjection(testInput);
    console.log(result);
    // Output: { sql: true, xss: false, type: 'sql', matches: [...] }
 */
declare function detectInjection(input: string, patternType?: string): {
    sql: boolean;
    xss: boolean;
    type: "sql" | "xss" | "mixed" | null;
    matches: {
        type: string;
        pattern: string;
        match: RegExpMatchArray | null;
    }[];
};

type CachedData = Record<string, any>;
interface MemoryCacheEntry {
    data: string;
    iv: string;
    authTag: string;
    timestamp: number;
    expiresAt: number;
    accessCount: number;
    lastAccessed: number;
    compressed: boolean;
    size: number;
    version: number;
}
interface CacheStats {
    hits: number;
    misses: number;
    evictions: number;
    totalSize: number;
    entryCount: number;
    hitRate: number;
    memoryUsage: {
        used: number;
        limit: number;
        percentage: number;
    };
    totalAccesses: number;
    size: number;
    capacity: number;
}
interface CacheOptions {
    ttl?: number;
    compress?: boolean;
    encrypt?: boolean;
}
/**
 * Options for file-based cache operations
 */
interface FileCacheOptions extends CacheOptions {
    maxCacheSize: number;
    /** Directory to store cache files (default: .data/cache) */
    directory?: string;
    /** File extension for cache files (default: .cache) */
    extension?: string;
    /** Enable atomic writes (write to temp file then rename) */
    atomic?: boolean;
    /** Enable file compression */
    compress?: boolean;
    /** Custom file naming strategy */
    namingStrategy?: "hash" | "direct" | "hierarchical" | "dated" | "flat";
    /** Maximum file size in bytes (default: 10MB) */
    maxFileSize?: number;
    /** Enable file metadata tracking */
    trackMetadata?: boolean;
}
/**
 * File cache entry metadata
 */
interface FileCacheMetadata {
    /** Original cache key */
    key: string;
    /** File creation timestamp */
    createdAt: number;
    /** Last access timestamp */
    lastAccessed: number;
    /** Expiration timestamp */
    expiresAt: number;
    /** File size in bytes */
    size: number;
    /** Number of times accessed */
    accessCount: number;
    /** Whether data is compressed */
    compressed: boolean;
    /** Whether data is encrypted */
    encrypted: boolean;
    /** Data type information */
    dataType: string;
    /** File version for migration support */
    version: number;
}
/**
 * File cache statistics
 */
interface FileCacheStats {
    /** Total number of cache files */
    fileCount: number;
    /** Total disk space used in bytes */
    totalSize: number;
    /** Number of cache hits */
    hits: number;
    /** Number of cache misses */
    misses: number;
    /** Number of expired files cleaned up */
    cleanups: number;
    /** Average file size in bytes */
    averageFileSize: number;
    /** Cache hit rate percentage */
    hitRate: number;
    /** Disk usage by directory */
    diskUsage: {
        used: number;
        available: number;
        percentage: number;
    };
    /** File age distribution */
    ageDistribution: {
        fresh: number;
        recent: number;
        old: number;
    };
    reads: number;
    writes: number;
    deletes: number;
    errors: number;
    totalFiles: number;
    avgResponseTime: number;
    lastCleanup: number;
}
/**
 * File cache cleanup options
 */
interface FileCacheCleanupOptions {
    /** Remove expired files */
    removeExpired?: boolean;
    /** Remove files older than specified age in milliseconds */
    maxAge?: number;
    /** Maximum number of files to keep (LRU cleanup) */
    maxFiles?: number;
    /** Maximum total size in bytes (size-based cleanup) */
    maxTotalSize?: number;
    /** Dry run mode (don't actually delete files) */
    dryRun?: boolean;
}
/**
 * File cache directory structure
 */
type FileCacheStrategy = "flat" | "hierarchical" | "dated" | "custom";

interface UltraMemoryCacheEntry extends MemoryCacheEntry {
    hotness: number;
    priority: number;
    tags: Set<string>;
    metadata: Record<string, any>;
    checksum: string;
}
interface UltraCacheOptions extends CacheOptions {
    priority?: number;
    tags?: string[];
    metadata?: Record<string, any>;
    skipEncryption?: boolean;
    skipCompression?: boolean;
    onEvict?: (key: string, value: CachedData) => void;
}
interface UltraStats extends CacheStats {
    averageAccessTime: number;
    compressionRatio: number;
    encryptionOverhead: number;
    hotKeys: string[];
    coldKeys: string[];
    tagStats: Map<string, number>;
}

/**
 * Secure In-Memory Cache (SIMC) v2.0
 *
 * Backward-compatible wrapper around UFSIMC that provides the same API as SIMC v1.0
 * while delivering significantly performance and advanced features.
 */

/**
 * Secure In-Memory Cache (SIMC) v2.0
 *
 * Now powered by Ultra-Fast Secure In-Memory Cache (UFSIMC) for significantly improved performance
 * while maintaining 100% backward compatibility with existing SIMC API.
 *
 * Performance improvements over SIMC v1.0:
 * - 10-50x faster cache operations through optimized algorithms
 * - Advanced hotness tracking and intelligent caching strategies
 * - Optimized memory management with object pooling
 * - Smart compression and encryption with minimal overhead
 * - Real-time performance monitoring and adaptive optimization
 * - Sub-millisecond cache hits with predictive prefetching
 */
declare class SIMC extends EventEmitter {
    private ultraCache;
    constructor();
    /**
     * Setup event forwarding from UFSIMC to maintain compatibility
     */
    private setupEventForwarding;
    /**
     * Convert SIMC options to UFSIMC-compatible format
     */
    private convertToUFSIMCOptions;
    /**
     * Convert UFSIMC stats to SIMC-compatible format
     */
    private convertToSIMCStats;
    /**
     * Validate and normalize cache key
     */
    private validateKey;
    /**
     * Store data in cache with optional TTL and compression
     *
     * with UFSIMC's intelligent caching strategies while maintaining
     * the exact same API as SIMC v1.0 for seamless backward compatibility.
     *
     * @param key - Unique identifier for the cached data
     * @param data - Data to cache (any serializable type)
     * @param options - Optional cache configuration
     * @returns Promise resolving to true if successful
     */
    set(key: string, data: CachedData, options?: Partial<CacheOptions>): Promise<boolean>;
    /**
     * Retrieve data from cache
     *
     * with UFSIMC's predictive prefetching and hotness tracking
     * for significantly faster retrieval times.
     *
     * @param key - Unique identifier for the cached data
     * @returns Promise resolving to cached data or null
     */
    get(key: string): Promise<CachedData | null>;
    /**
     * Delete entry from cache
     *
     * @param key - Cache key to remove
     * @returns True if entry was deleted, false otherwise
     */
    delete(key: string): boolean;
    /**
     * Check if key exists in cache
     *
     * @param key - Cache key to check
     * @returns True if key exists and is not expired
     */
    has(key: string): boolean;
    /**
     * Clear all cache entries
     */
    clear(): void;
    /**
     * Get cache statistics in SIMC v1.0 compatible format
     *
     * with additional performance metrics from UFSIMC
     * while maintaining the same return structure for compatibility.
     *
     * @returns Cache statistics
     */
    get getStats(): CacheStats;
    /**
     * Get cache size information
     *
     * @returns Object with entries count and total bytes
     */
    get size(): {
        entries: number;
        bytes: number;
    };
    /**
     * Clean up expired entries
     *
     * with UFSIMC's intelligent cleanup strategies.
     * Note: UFSIMC handles cleanup automatically, this method is for compatibility.
     *
     * @returns Number of entries cleaned up (estimated based on stats)
     */
    cleanup(): number;
    /**
     * Shutdown cache and cleanup resources
     *
     * Properly shuts down UFSIMC and cleans up all resources.
     */
    shutdown(): void;
}

declare const LOG_LEVELS: readonly ["silent", "error", "warn", "info", "debug", "verbose"];
type LogLevel = (typeof LOG_LEVELS)[number];
declare const LOG_COMPONENTS: readonly ["middleware", "server", "cache", "cluster", "performance", "fileWatcher", "plugins", "security", "monitoring", "routes", "userApp", "typescript", "console", "other", "router"];
type LogComponent = (typeof LOG_COMPONENTS)[number];
declare const LOG_TYPES: readonly ["startup", "warnings", "errors", "performance", "debug", "hotReload", "portSwitching"];
type LogType = (typeof LOG_TYPES)[number];

interface ClusterConfig {
    enabled?: boolean;
    workers?: number | "auto";
    processManagement?: {
        respawn?: boolean;
        maxRestarts?: number;
        restartDelay?: number;
        gracefulShutdownTimeout?: number;
        killTimeout?: number;
        zombieDetection?: boolean;
        memoryThreshold?: string;
        cpuThreshold?: number;
    };
    healthCheck?: {
        enabled?: boolean;
        interval?: number;
        timeout?: number;
        maxFailures?: number;
        endpoint?: string;
        customCheck?: (worker: any) => Promise<boolean>;
    };
    loadBalancing?: {
        strategy?: "round-robin" | "least-connections" | "ip-hash" | "weighted" | "adaptive" | "least-response-time" | "resource-based";
        weights?: number[];
        stickySession?: boolean;
        sessionAffinityKey?: string;
        circuitBreakerThreshold?: number;
        circuitBreakerTimeout?: number;
    };
    ipc?: {
        enabled?: boolean;
        channel?: string;
        messageQueue?: {
            maxSize?: number;
            timeout?: number;
        };
        broadcast?: boolean;
        events?: {
            [eventName: string]: (data: any, workerId: string) => void;
        };
    };
    autoScaling?: {
        enabled?: boolean;
        minWorkers?: number;
        maxWorkers?: number;
        scaleUpThreshold?: {
            cpu?: number;
            memory?: number;
            responseTime?: number;
            queueLength?: number;
        };
        scaleDownThreshold?: {
            cpu?: number;
            memory?: number;
            idleTime?: number;
        };
        cooldownPeriod?: number;
        scaleStep?: number;
    };
    resources?: {
        maxMemoryPerWorker?: string;
        maxCpuPerWorker?: number;
        priorityLevel?: "low" | "normal" | "high" | "critical";
        fileDescriptorLimit?: number;
        networkConnections?: {
            max?: number;
            timeout?: number;
        };
    };
    monitoring?: {
        enabled?: boolean;
        collectMetrics?: boolean;
        metricsInterval?: number;
        logLevel?: "error" | "warn" | "info" | "debug" | "trace";
        logWorkerEvents?: boolean;
        logPerformance?: boolean;
        customMetrics?: {
            [metricName: string]: (workerId: string) => number;
        };
    };
    errorHandling?: {
        uncaughtException?: "restart" | "log" | "ignore";
        unhandledRejection?: "restart" | "log" | "ignore";
        customErrorHandler?: (error: Error, workerId: string) => void;
        errorThreshold?: number;
        crashRecovery?: {
            enabled?: boolean;
            saveState?: boolean;
            stateStorage?: "memory" | "redis" | "file";
        };
    };
    security?: {
        isolateWorkers?: boolean;
        sandboxMode?: boolean;
        resourceLimits?: boolean;
        preventForkBombs?: boolean;
        workerAuthentication?: boolean;
        encryptIPC?: boolean;
    };
    development?: {
        hotReload?: boolean;
        debugMode?: boolean;
        profiling?: boolean;
        inspectPorts?: number[];
    };
    resilience?: {
        circuitBreaker?: {
            enabled?: boolean;
            failureThreshold?: number;
            recoveryTimeout?: number;
            halfOpenRequests?: number;
        };
        bulkhead?: {
            enabled?: boolean;
            maxConcurrentRequests?: number;
            queueSize?: number;
        };
        timeout?: {
            enabled?: boolean;
            requestTimeout?: number;
            healthCheckTimeout?: number;
        };
        retryPolicy?: {
            enabled?: boolean;
            maxRetries?: number;
            backoffStrategy?: "linear" | "exponential" | "constant";
            baseDelay?: number;
            maxDelay?: number;
        };
    };
    advanced?: {
        stateSync?: {
            enabled?: boolean;
            strategy?: "redis" | "gossip" | "consensus";
            syncInterval?: number;
        };
        deployment?: {
            rollingUpdates?: boolean;
            maxUnavailable?: number;
            maxSurge?: number;
            healthCheckGracePeriod?: number;
        };
        networking?: {
            tcpNoDelay?: boolean;
            keepAlive?: boolean;
            keepAliveInitialDelay?: number;
        };
    };
    persistence?: {
        enabled?: boolean;
        type?: "redis" | "file" | "memory" | "custom";
        redis?: {
            host?: string;
            port?: number;
            password?: string;
            db?: number;
            keyPrefix?: string;
            ttl?: number;
        };
        file?: {
            path?: string;
            backup?: boolean;
            maxBackups?: number;
            compression?: boolean;
        };
        memory?: {
            maxSize?: number;
            ttl?: number;
        };
        custom?: {
            saveHandler?: (state: any) => Promise<void>;
            loadHandler?: () => Promise<any>;
        };
    };
}

/**
 * Type definitions for Console Interception System
 */

/**
 * Enhanced preserve option configuration
 * Provides fine-grained control over console output behavior
 */
interface PreserveOption {
    enabled: boolean;
    mode: "original" | "intercepted" | "both" | "none";
    showPrefix: boolean;
    allowDuplication: boolean;
    customPrefix?: string;
    separateStreams: boolean;
    onlyUserApp: boolean;
    colorize: boolean;
}
interface ConsoleEncryptionConfig {
    enabled?: boolean;
    algorithm?: "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm";
    keyDerivation?: "pbkdf2" | "scrypt" | "argon2";
    iterations?: number;
    saltLength?: number;
    ivLength?: number;
    tagLength?: number;
    encoding?: "base64" | "hex";
    key?: string;
    displayMode?: "readable" | "encrypted" | "both";
    showEncryptionStatus?: boolean;
    externalLogging?: {
        enabled?: boolean;
        endpoint?: string;
        headers?: Record<string, string>;
        batchSize?: number;
        flushInterval?: number;
    };
}
interface ConsoleInterceptionConfig {
    enabled: boolean;
    interceptMethods: readonly ("log" | "error" | "warn" | "info" | "debug" | "trace")[];
    preserveOriginal: boolean | PreserveOption;
    filterUserCode: boolean;
    performanceMode: boolean;
    sourceMapping: boolean;
    stackTrace: boolean;
    maxInterceptionsPerSecond: number;
    encryption?: ConsoleEncryptionConfig;
    filters: {
        minLevel: "debug" | "info" | "warn" | "error";
        maxLength: number;
        includePatterns: readonly string[];
        excludePatterns: readonly string[];
        userAppPatterns?: readonly string[];
        systemPatterns?: readonly string[];
        categoryBehavior?: {
            userApp?: "intercept" | "passthrough" | "both";
            system?: "intercept" | "passthrough" | "both";
            unknown?: "intercept" | "passthrough" | "both";
        };
    };
    fallback: {
        onError: "silent" | "console" | "throw";
        gracefulDegradation: boolean;
        maxErrors: number;
    };
}

/**
 * @fileoverview Core type definitions for XyPrissJS Express integration
 *
 * This module contains fundamental types and utilities used throughout
 * the Express integration system.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */

/**
 * Deep partial utility type that makes all properties optional recursively.
 *
 * This utility type is used throughout the configuration system to allow
 * partial configuration objects while maintaining type safety.
 *
 * @template T - The type to make deeply partial
 *
 * @example
 * ```typescript
 * interface Config {
 *   server: {
 *     port: number;
 *     host: string;
 *   };
 * }
 *
 * type PartialConfig = DeepPartial<Config>;
 * // Result: { server?: { port?: number; host?: string; } }
 * ```
 */
type DeepPartial<T> = {
    [K in keyof T]?: T[K] extends infer U ? U extends object ? U extends readonly any[] ? U extends readonly (infer V)[] ? readonly DeepPartial<V>[] : U : U extends Function ? U : DeepPartial<U> : U : never;
};

/**
 * @fileoverview Cache-related type definitions for XyPrissJS Express integration
 *
 * This module contains all cache-related types including configuration,
 * strategies, metrics, and backend implementations.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */

/**
 * Memory cache configuration.
 *
 * Configuration for in-memory caching including eviction
 * policies and memory management.
 *
 * @interface MemoryConfig
 *
 * @example
 * ```typescript
 * const memoryConfig: MemoryConfig = {
 *   maxSize: 1024 * 1024 * 50, // 50MB
 *   algorithm: 'lru',
 *   evictionPolicy: 'lru',
 *   checkPeriod: 60000, // 1 minute
 *   preallocation: true
 * };
 * ```
 */
interface MemoryConfig$1 {
    /** Maximum memory size in bytes */
    maxSize?: number;
    /** Heap size allocation in bytes (alias for maxSize) */
    heapSize?: number;
    /** Cleanup interval in milliseconds (alias for checkPeriod) */
    cleanupInterval?: number;
    /** Cache algorithm */
    algorithm?: "lru" | "lfu" | "fifo";
    /** Eviction policy when cache is full */
    evictionPolicy?: "lru" | "lfu" | "fifo" | "ttl";
    /** Check period for expired entries in milliseconds */
    checkPeriod?: number;
    /** Enable memory preallocation for better performance */
    preallocation?: boolean;
}

/**
 * @fileoverview Middleware-related type definitions for XyPrissJS Express integration
 *
 * This module contains all middleware-related types including configuration,
 * management, statistics, and execution contexts.
 *
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 */

/**
 * Main middleware configuration interface.
 *
 * Comprehensive configuration for all middleware types
 * including built-in and custom middleware.
 *
 * @interface MiddlewareConfiguration
 *
 * @example
 * ```typescript
 * const middlewareConfig: MiddlewareConfiguration = {
 *   rateLimit: {
 *     enabled: true,
 *     windowMs: 900000, // 15 minutes
 *     max: 100
 *   },
 *   cors: {
 *     enabled: true,
 *     origin: ['https://example.com'],
 *     credentials: true
 *   },
 *   compression: {
 *     enabled: true,
 *     level: 6,
 *     threshold: 1024
 *   },
 *   enableOptimization: true,
 *   enableCaching: true,
 *   enablePerformanceTracking: true
 * };
 * ```
 */
interface MiddlewareConfiguration {
    /** Rate limiting middleware configuration */
    rateLimit?: boolean | RateLimitMiddlewareOptions;
    /** CORS middleware configuration */
    cors?: boolean | CorsMiddlewareOptions;
    /** Compression middleware configuration */
    compression?: boolean | CompressionMiddlewareOptions;
    /** Security middleware configuration */
    security?: boolean | SecurityMiddlewareOptions;
    /** Enable Helmet.js security headers */
    helmet?: boolean;
    /** Custom headers to add to all responses */
    customHeaders?: Record<string, string>;
    /** Enable middleware optimization */
    enableOptimization?: boolean;
    /** Enable middleware caching */
    enableCaching?: boolean;
    /** Enable performance tracking for middleware */
    enablePerformanceTracking?: boolean;
}
/**
 * Security middleware options interface.
 *
 * Configuration for security-related middleware including
 * Helmet, CORS, rate limiting, and custom security headers.
 *
 * @interface SecurityMiddlewareOptions
 *
 * @example
 * ```typescript
 * const securityOptions: SecurityMiddlewareOptions = {
 *   helmet: true,
 *   cors: {
 *     enabled: true,
 *     origin: ['https://trusted-domain.com']
 *   },
 *   rateLimit: {
 *     enabled: true,
 *     max: 100,
 *     windowMs: 900000
 *   },
 *   customHeaders: {
 *     'X-Custom-Security': 'enabled'
 *   },
 *   csrfProtection: true,
 *   contentSecurityPolicy: true,
 *   hsts: true
 * };
 * ```
 */
interface SecurityMiddlewareOptions {
    /** Helmet.js configuration */
    helmet?: boolean | any;
    /** CORS configuration */
    cors?: boolean | CorsMiddlewareOptions;
    /** Rate limiting configuration */
    rateLimit?: boolean | RateLimitMiddlewareOptions;
    /** Custom security headers */
    customHeaders?: Record<string, string>;
    /** Enable CSRF protection */
    csrfProtection?: boolean;
    /** Content Security Policy configuration */
    contentSecurityPolicy?: boolean | any;
    /** HTTP Strict Transport Security configuration */
    hsts?: boolean | any;
}
/**
 * Compression middleware options interface.
 *
 * Configuration for response compression including
 * compression levels, thresholds, and filters.
 *
 * @interface CompressionMiddlewareOptions
 *
 * @example
 * ```typescript
 * const compressionOptions: CompressionMiddlewareOptions = {
 *   enabled: true,
 *   level: 6, // Balanced compression
 *   threshold: 1024, // Only compress responses > 1KB
 *   filter: (req, res) => {
 *     // Custom filter logic
 *     return req.headers['x-no-compression'] ? false : true;
 *   },
 *   chunkSize: 16384,
 *   windowBits: 15,
 *   memLevel: 8,
 *   strategy: 0
 * };
 * ```
 */
interface CompressionMiddlewareOptions {
    /** Enable compression */
    enabled?: boolean;
    /** Compression level (0-9, higher = better compression) */
    level?: number;
    /** Minimum response size to compress (bytes) */
    threshold?: number;
    /** Custom filter function for compression */
    filter?: (req: Request, res: Response) => boolean;
    /** Chunk size for compression */
    chunkSize?: number;
    /** Window bits for compression algorithm */
    windowBits?: number;
    /** Memory level for compression */
    memLevel?: number;
    /** Compression strategy */
    strategy?: number;
}
/**
 * Rate limiting middleware options interface.
 *
 * Configuration for rate limiting including time windows,
 * limits, and custom logic.
 *
 * @interface RateLimitMiddlewareOptions
 *
 * @example
 * ```typescript
 * const rateLimitOptions: RateLimitMiddlewareOptions = {
 *   enabled: true,
 *   windowMs: 900000, // 15 minutes
 *   max: 100, // 100 requests per window
 *   message: 'Too many requests from this IP',
 *   standardHeaders: true,
 *   legacyHeaders: false,
 *   keyGenerator: (req) => req.ip,
 *   skip: (req) => req.ip === '127.0.0.1',
 *   onLimitReached: (req, res) => {
 *     console.log(`Rate limit exceeded for ${req.ip}`);
 *   }
 * };
 * ```
 */
interface RateLimitMiddlewareOptions {
    /** Enable rate limiting */
    enabled?: boolean;
    /** Time window in milliseconds */
    windowMs?: number;
    /** Maximum requests per window */
    max?: number;
    /** Message when limit is exceeded */
    message?: string;
    /** Include standard rate limit headers */
    standardHeaders?: boolean;
    /** Include legacy rate limit headers */
    legacyHeaders?: boolean;
    /** Custom key generator function */
    keyGenerator?: (req: Request) => string;
    /** Function to skip rate limiting for certain requests */
    skip?: (req: Request) => boolean;
    /** Callback when rate limit is reached */
    onLimitReached?: (req: Request, res: Response) => void;
}
/**
 * CORS middleware options interface.
 *
 * Configuration for Cross-Origin Resource Sharing including
 * origins, methods, headers, and credentials.
 *
 * @interface CorsMiddlewareOptions
 *
 * @example
 * ```typescript
 * const corsOptions: CorsMiddlewareOptions = {
 *   enabled: true,
 *   origin: (origin, callback) => {
 *     const allowedOrigins = ['https://example.com', 'https://app.example.com'];
 *     if (!origin || allowedOrigins.includes(origin)) {
 *       callback(null, true);
 *     } else {
 *       callback(new Error('Not allowed by CORS'));
 *     }
 *   },
 *   methods: ['GET', 'POST', 'PUT', 'DELETE'],
 *   allowedHeaders: ['Content-Type', 'Authorization'],
 *   exposedHeaders: ['X-Total-Count'],
 *   credentials: true,
 *   maxAge: 86400, // 24 hours
 *   preflightContinue: false,
 *   optionsSuccessStatus: 204
 * };
 * ```
 */
interface CorsMiddlewareOptions {
    /** Enable CORS */
    enabled?: boolean;
    /** Allowed origins */
    origin?: string | string[] | boolean | ((origin: string, callback: (err: Error | null, allow?: boolean) => void) => void);
    /** Allowed HTTP methods */
    methods?: string[];
    /** Allowed request headers */
    allowedHeaders?: string[];
    /** Headers exposed to the client */
    exposedHeaders?: string[];
    /** Allow credentials in CORS requests */
    credentials?: boolean;
    /** Cache duration for preflight requests in seconds */
    maxAge?: number;
    /** Pass control to next handler for preflight requests */
    preflightContinue?: boolean;
    /** Status code for successful OPTIONS requests */
    optionsSuccessStatus?: number;
}

/**
 * XyPrissJS Express Types - Main Export File
 *
 * This file serves as the main entry point for all Express integration types.
 * Types are now organized into MOD files for better maintainability.
 *
 * @fileoverview Main type export file for Express integration
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 *
 * @example
 * ```typescript
 * import { ServerOptions, UltraFastApp } from './types';
 * // or import specific modules
 * import { CacheConfig } from './types/cache';
 * import { SecurityConfig } from './types/security';
 * ```
 */

/**
 * @fileoverview Comprehensive server options interface for XyPrissJS Express integration
 *
 * This interface provides complete configuration options for creating ultra-fast,
 * secure Express servers with advanced features including caching, clustering,
 * performance optimization, and Go integration.
 *
 * @interface ServerOptions
 * @version 4.5.11
 * @author XyPrissJS Team
 * @since 2025-01-06
 *
 * @example
 * ```typescript
 * import { createServer, ServerOptions } from 'xypriss';
 *
 * const serverOptions: ServerOptions = {
 *   env: 'production',
 *   cache: {
 *     strategy: 'hybrid',
 *     maxSize: 1024 * 1024 * 100, // 100MB
 *     ttl: 3600,
 *     enabled: true,
 *     enableCompression: true
 *   },
 *   security: {
 *     encryption: true,
 *     cors: true,
 *     helmet: true
 *   },
 *   performance: {
 *     optimizationEnabled: true,
 *     aggressiveCaching: true,
 *     parallelProcessing: true
 *   },
 *   server: {
 *     port: 3000,
 *     host: '0.0.0.0',
 *     autoPortSwitch: {
 *       enabled: true,
 *       maxAttempts: 5
 *     }
 *   }
 * };
 *
 * const app = createServer(serverOptions);
 * ```
 */
interface ServerOptions {
    /**
     * Environment mode for the server.
     *
     * Determines the runtime environment and enables environment-specific
     * optimizations and configurations.
     *
     * @default 'development'
     *
     * @example
     * ```typescript
     * env: 'production' // Enables production optimizations
     * ```
     */
    env?: "development" | "production" | "test";
    /**
     * Cache configuration for ultra-fast data access.
     *
     * Comprehensive caching system supporting multiple backends,
     * compression, and intelligent strategies.
     *
     * @example
     * ```typescript
     * cache: {
     *   strategy: 'hybrid', // Memory + Redis
     *   maxSize: 1024 * 1024 * 100, // 100MB
     *   ttl: 3600, // 1 hour
     *   enabled: true,
     *   enableCompression: true,
     *   compressionLevel: 6,
     *   redis: {
     *     host: 'localhost',
     *     port: 6379,
     *     cluster: true,
     *     nodes: [
     *       { host: 'redis-1', port: 6379 },
     *       { host: 'redis-2', port: 6379 }
     *     ]
     *   },
     *   memory: {
     *     heapSize: 1024 * 1024 * 50, // 50MB
     *     cleanupInterval: 60000 // 1 minute
     *   }
     * }
     * ```
     */
    cache?: {
        /** Maximum cache size in bytes */
        maxSize?: number;
        /** Cache strategy selection */
        strategy?: "auto" | "memory" | "redis" | "hybrid" | "distributed";
        /** Default TTL in seconds */
        ttl?: number;
        /** Redis configuration */
        redis?: {
            /** Redis server hostname */
            host?: string;
            /** Redis server port */
            port?: number;
            /** Redis authentication password */
            password?: string;
            /** Enable Redis cluster mode */
            cluster?: boolean;
            /** Cluster node configurations */
            nodes?: Array<{
                host: string;
                port: number;
            }>;
        };
        /** Memory cache configuration */
        memory?: MemoryConfig$1;
        /** Enable caching system */
        enabled?: boolean;
        /** Enable cache compression */
        enableCompression?: boolean;
        /** Compression level (0-9) */
        compressionLevel?: number;
    };
    /**
     * Security configuration for comprehensive protection.
     *
     * Enables various security features including encryption,
     * monitoring, and standard security headers.
     *
     * @example
     * ```typescript
     * security: {
     *   encryption: true, // Enable data encryption
     *   accessMonitoring: true, // Monitor access patterns
     *   sanitization: true, // Sanitize inputs
     *   auditLogging: true, // Log security events
     *   cors: true, // Enable CORS protection
     *   helmet: true // Enable Helmet.js security headers
     * }
     * ```
     */
    security?: {
        /** Enable data encryption */
        encryption?: boolean;
        /** Enable access pattern monitoring */
        accessMonitoring?: boolean;
        /** Enable input sanitization */
        sanitization?: boolean;
        /** Enable security audit logging */
        auditLogging?: boolean;
        /** Enable CORS protection */
        cors?: boolean;
        /** Enable Helmet.js security headers */
        helmet?: boolean;
    };
    /**
     * Performance optimization configuration.
     *
     * Advanced performance features for ultra-fast execution,
     * intelligent caching, and request optimization.
     *
     * @example
     * ```typescript
     * performance: {
     *   optimizationEnabled: true,
     *   aggressiveCaching: true,
     *   parallelProcessing: true,
     *   preCompilerEnabled: true,
     *   learningPeriod: 300000, // 5 minutes
     *   optimizationThreshold: 1000, // requests
     *   workers: {
     *     cpu: 4,
     *     io: 8
     *   },
     *   ultraFastRulesEnabled: true,
     *   staticRouteOptimization: true,
     *   patternRecognitionEnabled: true
     * }
     * ```
     */
    performance?: {
        /** Enable response compression */
        compression?: boolean;
        /** Batch size for bulk operations */
        batchSize?: number;
        /** Enable connection pooling */
        connectionPooling?: boolean;
        /** Enable asynchronous write operations */
        asyncWrite?: boolean;
        /** Enable data prefetching */
        prefetch?: boolean;
        /** Worker configuration */
        workers?: {
            /** Number of CPU workers */
            cpu?: number;
            /** Number of I/O workers */
            io?: number;
        };
        /** Enable general optimization */
        optimizationEnabled?: boolean;
        /** Enable request classification */
        requestClassification?: boolean;
        /** Enable predictive preloading */
        predictivePreloading?: boolean;
        /** Enable aggressive caching */
        aggressiveCaching?: boolean;
        /** Enable parallel processing */
        parallelProcessing?: boolean;
        /** Enable request pre-compiler */
        preCompilerEnabled?: boolean;
        /** Learning period for optimization in milliseconds */
        learningPeriod?: number;
        /** Number of requests before optimization kicks in */
        optimizationThreshold?: number;
        /** Enable aggressive optimization mode */
        aggressiveOptimization?: boolean;
        /** Maximum number of compiled routes */
        maxCompiledRoutes?: number;
        /** Enable ultra-fast rules */
        ultraFastRulesEnabled?: boolean;
        /** Enable static route optimization */
        staticRouteOptimization?: boolean;
        /** Enable pattern recognition */
        patternRecognitionEnabled?: boolean;
        /** Enable cache warmup */
        cacheWarmupEnabled?: boolean;
        /** Warmup cache on startup */
        warmupOnStartup?: boolean;
        /** Precompute common responses */
        precomputeCommonResponses?: boolean;
        /** Custom health data provider */
        customHealthData?: () => any | Promise<any>;
        /** Custom status data provider */
        customStatusData?: () => any | Promise<any>;
    };
    monitoring?: {
        enabled?: boolean;
        healthChecks?: boolean;
        metrics?: boolean;
        detailed?: boolean;
        alertThresholds?: {
            memoryUsage?: number;
            hitRate?: number;
            errorRate?: number;
            latency?: number;
        };
    };
    server?: {
        port?: number;
        host?: string;
        trustProxy?: boolean;
        jsonLimit?: string;
        urlEncodedLimit?: string;
        enableMiddleware?: boolean;
        autoParseJson?: boolean;
        logPerfomances?: boolean;
        serviceName?: string;
        version?: string;
        autoPortSwitch?: {
            enabled?: boolean;
            maxAttempts?: number;
            startPort?: number;
            portRange?: [number, number];
            strategy?: "increment" | "random" | "predefined";
            predefinedPorts?: number[];
            onPortSwitch?: (originalPort: number, newPort: number) => void;
        };
    };
    /**
     * Request management configuration for handling timeouts, network quality, and request lifecycle
     *
     * @example
     * ```typescript
     * requestManagement: {
     *   timeout: {
     *     enabled: true,
     *     defaultTimeout: 30000, // 30 seconds
     *     routes: {
     *       "/api/upload": 300000, // 5 minutes for uploads
     *       "/api/quick": 5000     // 5 seconds for quick endpoints
     *     }
     *   },
     *   networkQuality: {
     *     enabled: true,
     *     rejectOnPoorConnection: true,
     *     minBandwidth: 1000, // 1KB/s minimum
     *     maxLatency: 2000    // 2 seconds max latency
     *   },
     *   concurrency: {
     *     maxConcurrentRequests: 1000,
     *     maxPerIP: 50,
     *     queueTimeout: 10000
     *   }
     * }
     * ```
     */
    requestManagement?: {
        /** Request timeout configuration */
        timeout?: {
            /** Enable request timeout management */
            enabled?: boolean;
            /** Default timeout for all requests in milliseconds */
            defaultTimeout?: number;
            /** Route-specific timeout overrides */
            routes?: Record<string, number>;
            /** Timeout for static file serving */
            staticTimeout?: number;
            /** Custom timeout handler */
            onTimeout?: (req: any, res: any) => void;
            /** Include stack trace in timeout errors */
            includeStackTrace?: boolean;
        };
        /** Network quality detection and management */
        networkQuality?: {
            /** Enable network quality monitoring */
            enabled?: boolean;
            /** Reject requests on poor network conditions */
            rejectOnPoorConnection?: boolean;
            /** Minimum bandwidth requirement in bytes/second */
            minBandwidth?: number;
            /** Maximum acceptable latency in milliseconds */
            maxLatency?: number;
            /** Network quality check interval in milliseconds */
            checkInterval?: number;
            /** Custom network quality handler */
            onPoorNetwork?: (req: any, res: any, metrics: any) => void;
        };
        /** Request concurrency management */
        concurrency?: {
            /** Maximum concurrent requests server-wide */
            maxConcurrentRequests?: number;
            /** Maximum concurrent requests per IP */
            maxPerIP?: number;
            /** Maximum time to wait in queue in milliseconds */
            queueTimeout?: number;
            /** Priority queue for different request types */
            priorityQueue?: {
                enabled?: boolean;
                priorities?: Record<string, number>;
            };
            /** Custom queue overflow handler */
            onQueueOverflow?: (req: any, res: any) => void;
        };
        /** Request lifecycle monitoring */
        lifecycle?: {
            /** Enable request lifecycle tracking */
            enabled?: boolean;
            /** Track request start time */
            trackStartTime?: boolean;
            /** Track request processing stages */
            trackStages?: boolean;
            /** Maximum request processing time before warning */
            warnAfter?: number;
            /** Custom lifecycle event handler */
            onLifecycleEvent?: (event: string, req: any, data: any) => void;
        };
        /** Request retry and circuit breaker */
        resilience?: {
            /** Enable request retry mechanism */
            retryEnabled?: boolean;
            /** Maximum retry attempts */
            maxRetries?: number;
            /** Retry delay in milliseconds */
            retryDelay?: number;
            /** Circuit breaker configuration */
            circuitBreaker?: {
                enabled?: boolean;
                failureThreshold?: number;
                resetTimeout?: number;
                monitoringPeriod?: number;
            };
        };
        /** Request size and payload management */
        payload?: {
            /** Maximum request body size in bytes */
            maxBodySize?: number;
            /** Maximum URL length */
            maxUrlLength?: number;
            /** Maximum number of form fields */
            maxFields?: number;
            /** Maximum file upload size */
            maxFileSize?: number;
            /** Allowed MIME types for uploads */
            allowedMimeTypes?: string[];
            /** Custom payload validation */
            customValidator?: (req: any) => boolean | Promise<boolean>;
        };
    };
    cluster?: {
        enabled?: boolean;
        config?: Omit<ClusterConfig, "enabled">;
    };
    fileWatcher?: {
        enabled?: boolean;
        watchPaths?: string[];
        ignorePaths?: string[];
        extensions?: string[];
        debounceMs?: number;
        restartDelay?: number;
        maxRestarts?: number;
        gracefulShutdown?: boolean;
        verbose?: boolean;
        typeCheck?: {
            enabled?: boolean;
            configFile?: string;
            checkOnSave?: boolean;
            checkBeforeRestart?: boolean;
            showWarnings?: boolean;
            showInfos?: boolean;
            maxErrors?: number;
            failOnError?: boolean;
            excludePatterns?: string[];
            includePatterns?: string[];
            verbose?: boolean;
        };
        typescript?: {
            enabled?: boolean;
            runner?: "auto" | "tsx" | "ts-node" | "bun" | "node" | string;
            runnerArgs?: string[];
            fallbackToNode?: boolean;
            autoDetectRunner?: boolean;
        };
    };
    middleware?: MiddlewareConfiguration;
    /**
     * Plugin system configuration for automatic optimization and maintenance
     *
     * @example
     * ```typescript
     * plugins: {
     *   routeOptimization: {
     *     enabled: true,
     *     optimizationThreshold: 100,
     *     autoOptimization: true,
     *     customRules: [
     *       {
     *         pattern: "/api/*",
     *         minHits: 50,
     *         maxResponseTime: 500,
     *         cacheStrategy: "aggressive"
     *       }
     *     ]
     *   },
     *   serverMaintenance: {
     *     enabled: true,
     *     errorThreshold: 5,
     *     memoryThreshold: 80,
     *     autoCleanup: true,
     *     logRetentionDays: 7
     *   }
     * }
     * ```
     */
    plugins?: {
        /** Route optimization plugin configuration */
        routeOptimization?: {
            /** Enable route optimization plugin */
            enabled?: boolean;
            /** How often to analyze routes in milliseconds */
            analysisInterval?: number;
            /** Minimum hits before optimization */
            optimizationThreshold?: number;
            /** Time window for popularity calculation in milliseconds */
            popularityWindow?: number;
            /** Maximum routes to track */
            maxTrackedRoutes?: number;
            /** Enable automatic optimization */
            autoOptimization?: boolean;
            /** Custom optimization rules */
            customRules?: Array<{
                pattern: string;
                minHits: number;
                maxResponseTime: number;
                cacheStrategy: "aggressive" | "moderate" | "conservative";
                preloadEnabled?: boolean;
            }>;
            /** Callback when route is optimized */
            onOptimization?: (route: string, optimization: string) => void;
            /** Callback when analysis is complete */
            onAnalysis?: (stats: any[]) => void;
        };
        /** Server maintenance plugin configuration */
        serverMaintenance?: {
            /** Enable server maintenance plugin */
            enabled?: boolean;
            /** How often to check health in milliseconds */
            checkInterval?: number;
            /** Error rate threshold percentage */
            errorThreshold?: number;
            /** Memory usage threshold percentage */
            memoryThreshold?: number;
            /** Response time threshold in milliseconds */
            responseTimeThreshold?: number;
            /** Log retention period in days */
            logRetentionDays?: number;
            /** Maximum log file size in bytes */
            maxLogFileSize?: number;
            /** Enable automatic cleanup */
            autoCleanup?: boolean;
            /** Enable automatic restart on critical issues */
            autoRestart?: boolean;
            /** Callback when issue is detected */
            onIssueDetected?: (issue: any) => void;
            /** Callback when maintenance is complete */
            onMaintenanceComplete?: (actions: string[]) => void;
        };
        /** Custom plugins */
        customPlugins?: Array<{
            name: string;
            plugin: any;
            config?: any;
        }>;
    };
    logging?: {
        enabled?: boolean;
        level?: "silent" | "error" | "warn" | "info" | "debug" | "verbose";
        components?: {
            server?: boolean;
            cache?: boolean;
            cluster?: boolean;
            performance?: boolean;
            fileWatcher?: boolean;
            plugins?: boolean;
            security?: boolean;
            monitoring?: boolean;
            routes?: boolean;
            userApp?: boolean;
            console?: boolean;
            other?: boolean;
            middleware?: boolean;
            router?: boolean;
            typescript?: boolean;
        };
        types?: {
            startup?: boolean;
            warnings?: boolean;
            errors?: boolean;
            performance?: boolean;
            debug?: boolean;
            hotReload?: boolean;
            portSwitching?: boolean;
        };
        format?: {
            timestamps?: boolean;
            colors?: boolean;
            prefix?: boolean;
            compact?: boolean;
        };
        consoleInterception?: DeepPartial<ConsoleInterceptionConfig>;
        customLogger?: (level: LogLevel, component: LogComponent, message: string, ...args: any[]) => void;
    };
    router?: {
        enabled?: boolean;
        precompileCommonRoutes?: boolean;
        enableSecurity?: boolean;
        enableCaching?: boolean;
        warmUpOnStart?: boolean;
        performance?: {
            targetResponseTime?: number;
            complexRouteTarget?: number;
            enableProfiling?: boolean;
            enableOptimizations?: boolean;
        };
        security?: {
            enableValidation?: boolean;
            enableSanitization?: boolean;
            enableRateLimit?: boolean;
            defaultRateLimit?: number;
        };
        cache?: {
            enabled?: boolean;
            defaultTTL?: number;
            maxCacheSize?: number;
        };
    };
    /**
     * Custom 404 error page configuration.
     *
     * Allows customization of the 404 Not Found page with beautiful XyPriss branding
     * while maintaining the "Powered by Nehonix" attribution.
     *
     * @example
     * ```typescript
     * notFound: {
     *   enabled: true,
     *   title: "Page Not Found",
     *   message: "The page you're looking for doesn't exist.",
     *   showSuggestions: true,
     *   customCSS: "body { background: linear-gradient(135deg, #667eea 0%, #764ba2 100%); }",
     *   redirectAfter: 5000, // Redirect to home after 5 seconds
     *   redirectTo: "/",
     *   showBackButton: true,
     *   theme: "dark" // "light" | "dark" | "auto"
     * }
     * ```
     */
    notFound?: {
        /** Enable custom 404 page (default: true) */
        enabled?: boolean;
        /** Custom page title (default: "Page Not Found - XyPriss") */
        title?: string;
        /** Custom message to display (default: "The page you're looking for doesn't exist.") */
        message?: string;
        /** Show helpful suggestions (readonly) */
        showSuggestions?: boolean;
        /** Custom CSS to inject into the page */
        customCSS?: string;
        /** Auto-redirect after specified milliseconds (disabled by default) */
        redirectAfter?: number;
        /** URL to redirect to (default: "/") */
        redirectTo?: string;
        /** Show back button (readonly) */
        showBackButton?: boolean;
        /** Theme preference (default: "auto") */
        theme?: "light" | "dark" | "auto";
        /** Custom logo URL (optional) */
        logoUrl?: string;
        /** Additional custom HTML content */
        customContent?: string;
        /** Contact information to display */
        contact?: {
            email?: string;
            website?: string;
            support?: string;
        };
    };
    /**
     * Network plugin configuration for enhanced networking capabilities.
     *
     * Provides comprehensive control over connection management, compression,
     * rate limiting, and proxy functionality features.
     *
     * @example
     * ```typescript
     * network: {
     *   connection: {
     *     http2: { enabled: true, maxConcurrentStreams: 100 },
     *     keepAlive: { enabled: true, timeout: 30000 },
     *     connectionPool: { maxConnections: 1000, timeout: 5000 }
     *   },
     *   compression: {
     *     enabled: true,
     *     algorithms: ["gzip", "deflate"],
     *     level: 6,
     *     threshold: 1024
     *   },
     *   rateLimit: {
     *     enabled: true,
     *     strategy: "sliding-window",
     *     global: { requests: 1000, window: "1h" },
     *     perIP: { requests: 100, window: "1m" }
     *   },
     *   proxy: {
     *     enabled: true,
     *     upstreams: [
     *       { host: "backend1.example.com", port: 8080, weight: 1 },
     *       { host: "backend2.example.com", port: 8080, weight: 2 }
     *     ],
     *     loadBalancing: "weighted-round-robin"
     *   }
     * }
     * ```
     */
    network?: {
        /**
         * Connection management plugin configuration.
         *
         * Handles HTTP/2 server push, keep-alive connections, and connection pooling
         * with intelligent resource detection and proper cache control.
         */
        connection?: {
            /** Enable connection plugin */
            enabled?: boolean;
            /** HTTP/2 configuration */
            http2?: {
                /** Enable HTTP/2 support */
                enabled?: boolean;
                /** Maximum concurrent streams per connection */
                maxConcurrentStreams?: number;
                /** Initial window size for flow control */
                initialWindowSize?: number;
                /** Enable server push */
                serverPush?: boolean;
            };
            /** Keep-alive configuration */
            keepAlive?: {
                /** Enable keep-alive connections */
                enabled?: boolean;
                /** Keep-alive timeout in milliseconds */
                timeout?: number;
                /** Maximum requests per connection */
                maxRequests?: number;
            };
            /** Connection pool configuration */
            connectionPool?: {
                /** Maximum number of connections */
                maxConnections?: number;
                /** Connection timeout in milliseconds */
                timeout?: number;
                /** Idle timeout in milliseconds */
                idleTimeout?: number;
            };
        };
        /**
         * Compression plugin configuration.
         *
         * Provides compression with multiple algorithms,
         * intelligent threshold detection, and proper content-type filtering.
         */
        compression?: {
            /** Enable compression plugin */
            enabled?: boolean;
            /** Supported compression algorithms */
            algorithms?: ("gzip" | "deflate" | "br")[];
            /** Compression level (1-9, higher = better compression, slower) */
            level?: number;
            /** Minimum response size to compress (bytes) */
            threshold?: number;
            /** Content types to compress */
            contentTypes?: string[];
            /** Memory level for compression (1-9) */
            memLevel?: number;
            /** Window size for compression */
            windowBits?: number;
        };
        /**
         * Rate limiting plugin configuration.
         *
         * Uses XyPriss cache system for distributed rate limiting with
         * secure key hashing and multiple limiting strategies.
         */
        rateLimit?: {
            /** Enable rate limiting plugin */
            enabled?: boolean;
            /** Rate limiting strategy */
            strategy?: "fixed-window" | "sliding-window" | "token-bucket";
            /** Global rate limits */
            global?: {
                /** Maximum requests per window */
                requests?: number;
                /** Time window (e.g., "1m", "1h", "1d") */
                window?: string;
            };
            /** Per-IP rate limits */
            perIP?: {
                /** Maximum requests per IP per window */
                requests?: number;
                /** Time window (e.g., "1m", "1h", "1d") */
                window?: string;
            };
            /** Per-user rate limits (requires authentication) */
            perUser?: {
                /** Maximum requests per user per window */
                requests?: number;
                /** Time window (e.g., "1m", "1h", "1d") */
                window?: string;
            };
            /** Custom rate limit headers */
            headers?: {
                /** Include rate limit headers in response */
                enabled?: boolean;
                /** Custom header prefix */
                prefix?: string;
            };
            /** Redis configuration for distributed rate limiting */
            redis?: {
                /** Redis host */
                host?: string;
                /** Redis port */
                port?: number;
                /** Redis password */
                password?: string;
                /** Redis database number */
                db?: number;
                /** Key prefix for rate limit data */
                keyPrefix?: string;
            };
        };
        /**
         * Proxy plugin configuration.
         *
         * Provides load balancing, health checks, and failover capabilities
         * with secure upstream selection and real HTTP health monitoring.
         */
        proxy?: {
            /** Enable proxy plugin */
            enabled?: boolean;
            /** Upstream servers configuration */
            upstreams?: Array<{
                /** Upstream server hostname */
                host: string;
                /** Upstream server port */
                port?: number;
                /** Server weight for load balancing */
                weight?: number;
                /** Maximum connections to this upstream */
                maxConnections?: number;
                /** Health check path */
                healthCheckPath?: string;
            }>;
            /** Load balancing strategy */
            loadBalancing?: "round-robin" | "weighted-round-robin" | "ip-hash" | "least-connections";
            /** Health check configuration */
            healthCheck?: {
                /** Enable health checks */
                enabled?: boolean;
                /** Health check interval in milliseconds */
                interval?: number;
                /** Health check timeout in milliseconds */
                timeout?: number;
                /** Health check path */
                path?: string;
                /** Unhealthy threshold (failed checks before marking unhealthy) */
                unhealthyThreshold?: number;
                /** Healthy threshold (successful checks before marking healthy) */
                healthyThreshold?: number;
            };
            /** Proxy timeout configuration */
            timeout?: number;
            /** Enable request/response logging */
            logging?: boolean;
            /** Custom error handling */
            onError?: (error: any, req: any, res: any) => void;
        };
    };
}

/**
 * Centralized Logger for FastApi.ts Server
 * Provides granular control over logging output
 */

declare class Logger {
    private config;
    private static instance;
    constructor(config?: ServerOptions["logging"]);
    /**
     * Get or create singleton instance
     */
    static getInstance(config?: ServerOptions["logging"]): Logger;
    /**
     * Deep merge two objects
     */
    private deepMerge;
    /**
     * Update logger configuration
     */
    updateConfig(config: ServerOptions["logging"]): void;
    /**
     * Get current logger configuration (for debugging)
     */
    getConfig(): ServerOptions["logging"];
    /**
     * Check if logging is enabled for a specific component and type
     */
    private shouldLog;
    /**
     * Format log message
     */
    private formatMessage;
    /**
     * Log a message
     */
    private log;
    error(component: LogComponent, message: string, ...args: any[]): void;
    warn(component: LogComponent, message: string, ...args: any[]): void;
    info(component: LogComponent, message: string, ...args: any[]): void;
    debug(component: LogComponent, message: string, ...args: any[]): void;
    startup(component: LogComponent, message: string, ...args: any[]): void;
    performance(component: LogComponent, message: string, ...args: any[]): void;
    hotReload(component: LogComponent, message: string, ...args: any[]): void;
    portSwitching(component: LogComponent, message: string, ...args: any[]): void;
    securityWarning(message: string, ...args: any[]): void;
    isEnabled(): boolean;
    getLevel(): LogLevel;
    isComponentEnabled(component: LogComponent): boolean;
    isTypeEnabled(type: LogType): boolean;
}

/**
 * Ultra-Fast Secure In-Memory Cache (UFSIMC)
 * Extends SIMC with extreme performance optimizations and advanced features
 */
declare class UFSIMC extends EventEmitter {
    private lru;
    private keyHashMap;
    private tagIndex;
    private priorityQueues;
    private hotnessDecayTimer?;
    private stats;
    private encryptionKey;
    private keyRotationTimer?;
    private cleanupTimer?;
    private securityTimer?;
    private performanceTimer?;
    private encryptionPool;
    private accessTimes;
    private accessPatterns;
    private rateLimiter;
    private integrityCheck;
    private anomalyThreshold;
    private logger;
    constructor(maxEntries?: number, logger?: Logger);
    /**
     * Warm up cipher pools for better performance
     */
    private warmUpPools;
    /**
     * Start performance monitoring
     */
    private startPerformanceMonitoring;
    /**
     * Enhanced encryption initialization with key derivation
     */
    private initializeEncryption;
    /**
     * Ultra-fast key validation and hashing
     */
    private validateAndHashKey;
    /**
     * High-performance compression with adaptive algorithms
     */
    private smartCompress;
    /**
     * Smart decompression
     */
    private smartDecompress;
    /**
     * High-performance encryption with pooling
     */
    private fastEncrypt;
    /**
     * High-performance decryption
     */
    private fastDecrypt;
    /**
     * Calculate data checksum for integrity
     */
    private calculateChecksum;
    /**
     * Rate limiting check
     */
    private checkRateLimit;
    /**
     * Ultra-fast SET operation with advanced features
     */
    set(key: string, value: CachedData, options?: UltraCacheOptions): Promise<boolean>;
    /**
     * Ultra-fast GET operation with hotness tracking
     */
    get(key: string): Promise<CachedData | null>;
    /**
     * Helper method for decryption and decompression
     */
    private decryptAndDecompress;
    /**
     * Batch GET operation for multiple keys
     */
    getMultiple(keys: string[]): Promise<Map<string, CachedData | null>>;
    /**
     * Set multiple key-value pairs
     */
    setMultiple(entries: Array<{
        key: string;
        value: CachedData;
        options?: UltraCacheOptions;
    }>): Promise<boolean[]>;
    /**
     * Delete by tag
     */
    deleteByTag(tag: string): Promise<number>;
    /**
     * Get keys by tag
     */
    getKeysByTag(tag: string): string[];
    /**
     * Advanced cache statistics
     */
    get getUltraStats(): UltraStats;
    /**
     * Export cache data for backup
     */
    exportData(): Promise<any>;
    /**
     * Import cache data from backup
     */
    importData(data: any): Promise<boolean>;
    /**
     * Performance and maintenance methods
     */
    private updatePerformanceMetrics;
    private updateHotColdKeys;
    private optimizeHotness;
    private decayHotness;
    private recordAccessTime;
    private updateStatsAfterSet;
    private trackAccess;
    private cleanupIndexes;
    private findOriginalKey;
    private startMaintenanceTasks;
    private cleanup;
    private rotateEncryptionKey;
    private performSecurityChecks;
    private emergencyCleanup;
    private detectAnomalies;
    /**
     * Get cache health report
     */
    getHealthReport(): {
        status: "healthy" | "warning" | "critical";
        issues: string[];
        recommendations: string[];
        metrics: UltraStats;
    };
    /**
     * Optimize cache configuration automatically
     */
    autoOptimize(): void;
    /**
     * Prefetch data based on access patterns
     */
    prefetch(predictor: (key: string, metadata: any) => Promise<CachedData | null>): Promise<number>;
    /**
     * Create a cache snapshot for debugging
     */
    createSnapshot(): any;
    /**
     * Validate cache integrity
     */
    validateIntegrity(): Promise<{
        valid: number;
        invalid: number;
        errors: string[];
    }>;
    /**
     * Enhanced delete with pattern matching
     */
    delete(key: string): boolean;
    /**
     * Delete with pattern (supports wildcards)
     */
    deletePattern(pattern: string): number;
    /**
     * Check if key exists
     */
    has(key: string): boolean;
    /**
     * Clear all entries
     */
    clear(): void;
    /**
     * Get cache size
     */
    get size(): {
        entries: number;
        bytes: number;
    };
    /**
     * Graceful shutdown
     */
    shutdown(): Promise<void>;
}

declare const CONFIG: {
    CACHE_EXPIRY_MS: number;
    KEY_ROTATION_MS: number;
    ALGORITHM: "aes-256-gcm";
    ENCODING: crypto.BinaryToTextEncoding;
    KEY_ITERATIONS: number;
    KEY_LENGTH: number;
    MAX_CACHE_SIZE_MB: number;
    MAX_ENTRIES: number;
    COMPRESSION_THRESHOLD_BYTES: number;
    CLEANUP_INTERVAL_MS: number;
    SECURITY_CHECK_INTERVAL_MS: number;
    MAX_KEY_LENGTH: number;
    MAX_VALUE_SIZE_MB: number;
};

/**
 * Default configuration for file-based cache
 */
declare const DEFAULT_FILE_CACHE_CONFIG: Required<FileCacheOptions>;

/**
 * Comprehensive File Cache System
 */
declare class FileCache {
    private config;
    private stats;
    constructor(options?: Partial<FileCacheOptions>);
    /**
     * Initialize cache statistics by scanning existing files
     */
    private initializeStats;
    /**
     * Ensure base cache directory exists
     */
    private ensureBaseDirectory;
    /**
     * Update cache statistics
     */
    private updateStats;
    /**
     * Update disk usage statistics
     */
    private updateDiskUsage;
    /**
     * Calculate directory size recursively
     */
    private getDirectorySize;
    /**
     * Update age distribution statistics
     */
    private updateAgeDistribution;
    /**
     * Write data to file cache
     */
    set(key: string, value: CachedData, options?: Partial<FileCacheOptions>): Promise<boolean>;
    /**
     * Read data from file cache
     */
    get(key: string, updatedContent?: boolean): Promise<CachedData | null>;
    /**
     * Delete cache entry
     */
    delete(key: string): Promise<boolean>;
    /**
     * Check if key exists and is not expired
     */
    has(key: string): Promise<boolean>;
    /**
     * Clear all cache files
     */
    clear(): Promise<void>;
    /**
     * Recursively delete directory
     */
    private deleteDirectory;
    /**
     * Cleanup expired entries
     */
    cleanup(_options?: Partial<FileCacheCleanupOptions>): Promise<{
        cleaned: number;
        errors: number;
        totalSize: number;
    }>;
    /**
     * Get all cache files recursively
     */
    private getAllCacheFiles;
    /**
     * Get cache statistics with real-time updates
     */
    getStats(): Promise<FileCacheStats>;
    /**
     * Get cache size information
     */
    get size(): {
        files: number;
        bytes: number;
    };
    /**
     * Get detailed cache information
     */
    getCacheInfo(): Promise<{
        config: Required<FileCacheOptions>;
        stats: FileCacheStats;
        health: {
            healthy: boolean;
            issues: string[];
            recommendations: string[];
        };
    }>;
}

/**
 * SecureCacheClient - Secure caching solution
 *
 * A high-performance, secure cache client that supports multiple backend strategies
 * including memory-only, Redis-only, and hybrid (memory + Redis) configurations.
 * Features military-grade AES-256-GCM encryption, intelligent compression, and
 * comprehensive monitoring capabilities.
 *
 * ## Features
 * - **Multi-Strategy Support**: Memory, Redis, or Hybrid caching
 * - **Military-Grade Security**: AES-256-GCM encryption with key rotation
 * - **High Availability**: Redis Cluster and Sentinel support
 * - **Performance Optimized**: Intelligent compression and hot data promotion
 * - **Production Ready**: Comprehensive monitoring and health checks
 * - **Type Safe**: Full TypeScript support with detailed interfaces
 *
 * ## Supported Cache Strategies
 * - `memory`: Ultra-fast in-memory caching with LRU eviction
 * - `redis`: Distributed Redis caching with clustering support
 * - `hybrid`: Memory-first with Redis backup for optimal performance
 *
 * ## Security Features
 * - AES-256-GCM encryption for all cached data
 * - Automatic key rotation and tamper detection
 * - Secure serialization with integrity verification
 * - Access pattern monitoring and anomaly detection
 *
 * @example Basic Redis Configuration
 * ```typescript
 * import { SecureCacheClient } from "xypriss-security";
 *
 * const cache = new SecureCacheClient({
 *   strategy: "redis",
 *   redis: {
 *     host: "localhost",
 *     port: 6379,
 *     password: "your-secure-password"
 *   }
 * });
 *
 * await cache.connect();
 * await cache.set("user:123", { name: "John", role: "admin" }, { ttl: 3600 });
 * const user = await cache.get("user:123");
 * ```
 *
 * @example Hybrid Strategy with Encryption
 * ```typescript
 * const cache = new SecureCacheClient({
 *   strategy: "hybrid",
 *   memory: {
 *     maxSize: 100, // 100MB
 *     maxEntries: 10000
 *   },
 *   redis: {
 *     host: "redis-cluster.example.com",
 *     port: 6379,
 *     cluster: {
 *       enabled: true,
 *       nodes: [
 *         { host: "redis-1", port: 6379 },
 *         { host: "redis-2", port: 6379 }
 *       ]
 *     }
 *   },
 *   security: {
 *     encryption: true,
 *     keyRotation: true
 *   }
 * });
 * ```
 *
 * @example Advanced Usage with Tags and Monitoring
 * ```typescript
 * // Store data with tags for bulk invalidation
 * await cache.set("product:123", productData, {
 *   ttl: 1800,
 *   tags: ["products", "category:electronics"]
 * });
 *
 * // Batch operations for better performance
 * await cache.mset({
 *   "user:1": userData1,
 *   "user:2": userData2
 * }, { ttl: 3600 });
 *
 * // Invalidate by tags
 * await cache.invalidateByTags(["products"]);
 *
 * // Monitor cache health
 * const health = cache.getHealth();
 * if (health.status !== "healthy") {
 *   console.warn("Cache issues:", health.details);
 * }
 *
 * // Get performance statistics
 * const stats = await cache.getStats();
 * console.log(`Hit rate: ${stats.memory.hitRate * 100}%`);
 * ```
 *
 * @since 4.2.3
 * @version 4.2.3
 * @author NEHONIX
 * @see {@link ICacheAdapter} for the complete interface definition
 * @see {@link https://lab.nehonix.space/nehonix_viewer/_doc/Nehonix%20XyPrissSecurity} for detailed documentation
 */
declare class SecureCacheClient {
    private adapter;
    private config;
    /**
     * Creates a new SecureCacheClient instance
     *
     * @param config - Cache configuration object
     * @param config.strategy - Cache strategy: "memory", "redis", or "hybrid"
     * @param config.redis - Redis configuration (required for "redis" and "hybrid" strategies)
     * @param config.redis.host - Redis server hostname
     * @param config.redis.port - Redis server port
     * @param config.redis.password - Redis authentication password
     * @param config.redis.cluster - Redis cluster configuration
     * @param config.memory - Memory cache configuration (for "memory" and "hybrid" strategies)
     * @param config.memory.maxSize - Maximum memory cache size in MB
     * @param config.memory.maxEntries - Maximum number of cache entries
     * @param config.security - Security configuration
     * @param config.security.encryption - Enable AES-256-GCM encryption
     * @param config.security.keyRotation - Enable automatic key rotation
     * @param config.monitoring - Monitoring and health check configuration
     *
     * @example
     * ```typescript
     * const cache = new SecureCacheClient({
     *   strategy: "hybrid",
     *   redis: { host: "localhost", port: 6379 },
     *   memory: { maxSize: 100, maxEntries: 10000 },
     *   security: { encryption: true }
     * });
     * ```
     */
    constructor(config: CacheConfig);
    /**
     * Ensures the cache adapter is initialized
     * @private
     * @returns Promise resolving to the initialized adapter
     */
    private ensureAdapter;
    /**
     * Retrieves a value from the cache
     *
     * @param key - The cache key to retrieve
     * @returns Promise resolving to the cached value, or null if not found
     *
     * @example
     * ```typescript
     * const user = await cache.read<User>("user:123");
     * if (user) {
     *   console.log("Found user:", user.name);
     * }
     * ```
     */
    read<T = any>(key: string): Promise<T | null>;
    /**
     * Retrieves a value from the cache (alias for get method)
     *
     * @param key - The cache key to retrieve
     * @returns Promise resolving to the cached value, or null if not found
     *
     * @example
     * ```typescript
     * const user = await cache.read<User>("user:123");
     * if (user) {
     *   console.log("Found user:", user.name);
     * }
     * ```
     */
    /**
     * Stores a value in the cache with optional TTL and tags
     *
     * @param key - The cache key to store the value under
     * @param value - The value to cache (will be automatically serialized)
     * @param options - Optional caching options
     * @param options.ttl - Time to live in seconds (default: configured TTL)
     * @param options.tags - Array of tags for bulk invalidation
     * @returns Promise resolving to true if successful, false otherwise
     *
     * @example
     * ```typescript
     * // Basic usage
     * await cache.write("user:123", { name: "John", role: "admin" });
     *
     * // With TTL (1 hour)
     * await cache.write("session:abc", sessionData, { ttl: 3600 });
     *
     * // With tags for bulk invalidation
     * await cache.write("product:456", productData, {
     *   ttl: 1800,
     *   tags: ["products", "category:electronics"]
     * });
     * ```
     */
    write<T = any>(key: string, value: T, options?: CacheSetOptions): Promise<boolean>;
    /**
     * Stores a value in the cache (alias for set method)
     *
     * @param key - The cache key to store the value under
     * @param value - The value to cache (will be automatically serialized)
     * @param options - Optional caching options
     * @param options.ttl - Time to live in seconds (default: configured TTL)
     * @param options.tags - Array of tags for bulk invalidation
     * @returns Promise resolving to true if successful, false otherwise
     *
     * @example
     * ```typescript
     * // Basic usage
     * await cache.write("user:123", { name: "John", role: "admin" });
     *
     * // With TTL (1 hour)
     * await cache.write("session:abc", sessionData, { ttl: 3600 });
     *
     * // With tags for bulk invalidation
     * await cache.write("product:456", productData, {
     *   ttl: 1800,
     *   tags: ["products", "category:electronics"]
     * });
     * ```
     */
    /**
     * Store encrypted session data with expiration (SETEX for sessions)
     *
     * This method provides secure session storage with automatic encryption,
     * expiration, and session-specific security features. Perfect for storing
     * user sessions, authentication tokens, and other sensitive temporary data.
     *
     * @param sessionKey - The session key (will be prefixed with 'session:')
     * @param sessionData - The session data to encrypt and store
     * @param ttlSeconds - Time to live in seconds (Redis SETEX style)
     * @param options - Optional session-specific options
     * @param options.userId - User ID for session tracking and validation
     * @param options.ipAddress - IP address for session validation
     * @param options.userAgent - User agent for session validation
     * @param options.encryptionKey - Custom encryption key (generates secure key if not provided)
     * @param options.tags - Array of tags for bulk invalidation
     * @returns Promise resolving to true if successful, false otherwise
     *
     * @example Basic Session Storage
     * ```typescript
     * interface UserSession {
     *   userId: string;
     *   username: string;
     *   roles: string[];
     *   loginTime: number;
     *   lastActivity: number;
     * }
     *
     * const sessionData: UserSession = {
     *   userId: "user123",
     *   username: "john_doe",
     *   roles: ["user", "admin"],
     *   loginTime: Date.now(),
     *   lastActivity: Date.now()
     * };
     *
     * // Store encrypted session for 1 hour (3600 seconds)
     * const success = await cache.setex("session_abc123def456", sessionData, 3600);
     * ```
     *
     * @example Advanced Session Storage with Validation
     * ```typescript
     * // Store session with additional security context
     * const success = await cache.setex("session_xyz789", sessionData, 7200, {
     *   userId: "user123",
     *   ipAddress: "192.168.1.100",
     *   userAgent: "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
     *   tags: ["sessions", "user123", "admin-session"]
     * });
     *
     * if (success) {
     *   console.log("Session stored securely with encryption");
     * }
     * ```
     *
     * @example Custom Encryption Key
     * ```typescript
     * import { XyPrissSecurity } from "xypriss-security";
     *
     * // Generate a custom encryption key for this session
     * const customKey = XyPrissSecurity.generateSecureToken({ length: 32 });
     *
     * const success = await cache.setex("session_custom", sessionData, 1800, {
     *   encryptionKey: customKey,
     *   userId: "user456",
     *   tags: ["premium-sessions"]
     * });
     * ```
     *
     * @since 4.2.3
     * @see {@link read} for retrieving session data
     * @see {@link delete} for removing sessions
     * @see {@link invalidateByTags} for bulk session invalidation
     */
    setex<T = any>(sessionKey: string, sessionData: T, ttlSeconds: number, options?: {
        userId?: string;
        ipAddress?: string;
        userAgent?: string;
        encryptionKey?: string;
        tags?: string[];
    }): Promise<boolean>;
    /**
     * Retrieve encrypted session data with automatic decryption and validation
     *
     * Retrieves and decrypts session data stored with the setex method.
     * Validates session integrity, expiration, and optional security context.
     *
     * @param sessionKey - The session key used when storing
     * @param encryptionKey - The encryption key used when storing (required for decryption)
     * @param options - Optional validation options for enhanced security
     * @param options.validateUserId - User ID to validate against stored session
     * @param options.validateIpAddress - IP address to validate against stored session
     * @param options.validateUserAgent - User agent to validate against stored session
     * @returns Promise resolving to decrypted session data, or null if not found/invalid
     *
     * @example Basic Session Retrieval
     * ```typescript
     * interface UserSession {
     *   userId: string;
     *   username: string;
     *   roles: string[];
     *   loginTime: number;
     * }
     *
     * // Retrieve session data (encryption key must match the one used in setex)
     * const sessionData = await cache.getSession<UserSession>(
     *   "session_abc123def456",
     *   encryptionKey
     * );
     *
     * if (sessionData) {
     *   console.log("Welcome back,", sessionData.username);
     *   console.log("Your roles:", sessionData.roles);
     * } else {
     *   console.log("Session not found or expired");
     * }
     * ```
     *
     * @example Session Retrieval with Security Validation
     * ```typescript
     * // Retrieve session with additional security checks
     * const sessionData = await cache.getSession<UserSession>(
     *   "session_xyz789",
     *   encryptionKey,
     *   {
     *     validateUserId: "user123",        // Must match stored user ID
     *     validateIpAddress: "192.168.1.100", // Must match stored IP
     *     validateUserAgent: req.headers['user-agent'] // Must match stored user agent
     *   }
     * );
     *
     * if (sessionData) {
     *   // Session is valid and security context matches
     *   console.log("Secure session validated for:", sessionData.username);
     * } else {
     *   // Session not found, expired, or security validation failed
     *   console.log("Session validation failed - possible security issue");
     * }
     * ```
     *
     * @example Express.js Middleware Usage
     * ```typescript
     * import { Request, Response, NextFunction } from 'express';
     *
     * async function sessionMiddleware(req: Request, res: Response, next: NextFunction) {
     *   const sessionId = req.cookies.sessionId;
     *   const encryptionKey = process.env.SESSION_ENCRYPTION_KEY;
     *
     *   if (!sessionId || !encryptionKey) {
     *     return res.status(401).json({ error: 'No session' });
     *   }
     *
     *   const sessionData = await cache.getSession(sessionId, encryptionKey, {
     *     validateIpAddress: req.ip,
     *     validateUserAgent: req.headers['user-agent']
     *   });
     *
     *   if (!sessionData) {
     *     return res.status(401).json({ error: 'Invalid session' });
     *   }
     *
     *   req.user = sessionData;
     *   next();
     * }
     * ```
     *
     * @since 4.2.3
     * @see {@link setex} for storing encrypted session data
     * @see {@link delete} for removing sessions
     */
    getSession<T = any>(sessionKey: string, encryptionKey: string, options?: {
        validateUserId?: string;
        validateIpAddress?: string;
        validateUserAgent?: string;
    }): Promise<T | null>;
    /**
     * Deletes a value from the cache
     *
     * @param key - The cache key to delete
     * @returns Promise resolving to true if the key was deleted, false if not found
     *
     * @example
     * ```typescript
     * const deleted = await cache.delete("user:123");
     * if (deleted) {
     *   console.log("User cache cleared");
     * }
     * ```
     */
    delete(key: string): Promise<boolean>;
    /**
     * Checks if a key exists in the cache
     *
     * @param key - The cache key to check
     * @returns Promise resolving to true if the key exists, false otherwise
     *
     * @example
     * ```typescript
     * if (await cache.exists("user:123")) {
     *   console.log("User is cached");
     * }
     * ```
     */
    exists(key: string): Promise<boolean>;
    /**
     * Clears all cached data
     *
     * ⚠️ **Warning**: This operation is irreversible and will remove all cached data
     *
     * @returns Promise that resolves when the cache is cleared
     *
     * @example
     * ```typescript
     * await cache.clear();
     * console.log("All cache data cleared");
     * ```
     */
    clear(): Promise<void>;
    /**
     * Establishes connection to the cache backend
     *
     * Must be called before using the cache. For Redis strategies, this establishes
     * the connection to the Redis server(s). For memory-only strategy, this initializes
     * the in-memory cache.
     *
     * @returns Promise that resolves when the connection is established
     * @throws {Error} If connection fails
     *
     * @example
     * ```typescript
     * try {
     *   await cache.connect();
     *   console.log("Cache connected successfully");
     * } catch (error) {
     *   console.error("Failed to connect to cache:", error);
     * }
     * ```
     */
    connect(): Promise<void>;
    /**
     * Closes the connection to the cache backend
     *
     * Gracefully closes all connections and cleans up resources. Should be called
     * when shutting down the application.
     *
     * @returns Promise that resolves when the connection is closed
     *
     * @example
     * ```typescript
     * process.on('SIGTERM', async () => {
     *   await cache.disconnect();
     *   console.log("Cache disconnected");
     * });
     * ```
     */
    disconnect(): Promise<void>;
    /**
     * Retrieves comprehensive cache performance statistics
     *
     * @returns Promise resolving to detailed statistics including hit rates, memory usage, and performance metrics
     *
     * @example
     * ```typescript
     * const stats = await cache.getStats();
     * console.log(`Memory hit rate: ${stats.memory.hitRate * 100}%`);
     * console.log(`Redis hit rate: ${stats.redis?.hitRate * 100}%`);
     * console.log(`Total operations: ${stats.operations.total}`);
     * console.log(`Average response time: ${stats.performance.avgResponseTime}ms`);
     * ```
     */
    getStats(): Promise<SecureCacheStats>;
    /**
     * Retrieves multiple values from the cache in a single operation
     *
     * @param keys - Array of cache keys to retrieve
     * @returns Promise resolving to an object with key-value pairs (missing keys are omitted)
     *
     * @example
     * ```typescript
     * const users = await cache.mread<User>(["user:1", "user:2", "user:3"]);
     * console.log(users); // { "user:1": {...}, "user:2": {...} }
     * ```
     */
    mread<T = any>(keys: string[]): Promise<Record<string, T>>;
    /**
     * Stores multiple key-value pairs in a single operation
     *
     * @param entries - Object with key-value pairs or array of [key, value] tuples
     * @param options - Optional caching options applied to all entries
     * @param options.ttl - Time to live in seconds for all entries
     * @param options.tags - Array of tags applied to all entries
     * @returns Promise resolving to true if successful, false otherwise
     *
     * @example
     * ```typescript
     * // Using object notation
     * await cache.mwrite({
     *   "user:1": { name: "Alice" },
     *   "user:2": { name: "Bob" }
     * }, { ttl: 3600 });
     *
     * // Using array notation
     * await cache.mwrite([
     *   ["session:abc", sessionData1],
     *   ["session:def", sessionData2]
     * ], { ttl: 1800, tags: ["sessions"] });
     * ```
     */
    mwrite<T = any>(entries: Record<string, T> | Array<[string, T]>, options?: CacheSetOptions): Promise<boolean>;
    /**
     * Invalidates all cache entries that have any of the specified tags
     *
     * @param tags - Array of tags to invalidate
     * @returns Promise resolving to the number of entries invalidated
     *
     * @example
     * ```typescript
     * // Invalidate all product-related cache entries
     * const count = await cache.invalidateByTags(["products", "inventory"]);
     * console.log(`Invalidated ${count} cache entries`);
     * ```
     */
    invalidateByTags(tags: string[]): Promise<number>;
    /**
     * Gets the remaining time-to-live for a cache key
     *
     * @param key - The cache key to check
     * @returns Promise resolving to TTL in seconds, or -1 if key doesn't exist, -2 if no TTL set
     *
     * @example
     * ```typescript
     * const ttl = await cache.getTTL("user:123");
     * if (ttl > 0) {
     *   console.log(`Key expires in ${ttl} seconds`);
     * }
     * ```
     */
    getTTL(key: string): Promise<number>;
    /**
     * Sets or updates the expiration time for a cache key
     *
     * @param key - The cache key to set expiration for
     * @param ttl - Time to live in seconds
     * @returns Promise resolving to true if successful, false if key doesn't exist
     *
     * @example
     * ```typescript
     * // Extend expiration to 1 hour
     * await cache.expire("user:123", 3600);
     *
     * // Set short expiration for temporary data
     * await cache.expire("temp:data", 60);
     * ```
     */
    expire(key: string, ttl: number): Promise<boolean>;
    /**
     * Retrieves all cache keys matching an optional pattern
     *
     * ⚠️ **Warning**: Use with caution in production as this can be expensive for large caches
     *
     * @param pattern - Optional glob-style pattern to filter keys (Redis syntax)
     * @returns Promise resolving to array of matching keys
     *
     * @example
     * ```typescript
     * // Get all keys
     * const allKeys = await cache.keys();
     *
     * // Get user-related keys
     * const userKeys = await cache.keys("user:*");
     *
     * // Get session keys with pattern
     * const sessionKeys = await cache.keys("session:*:active");
     * ```
     */
    keys(pattern?: string): Promise<string[]>;
    /**
     * Gets the current health status of the cache system
     *
     * @returns Health status object with overall status and detailed information
     *
     * @example
     * ```typescript
     * const health = cache.getHealth();
     *
     * switch (health.status) {
     *   case "healthy":
     *     console.log("Cache is operating normally");
     *     break;
     *   case "degraded":
     *     console.warn("Cache has issues but is functional:", health.details);
     *     break;
     *   case "unhealthy":
     *     console.error("Cache is not functional:", health.details);
     *     break;
     * }
     *
     * // Check specific metrics
     * if (health.details.redis?.connected === false) {
     *   console.error("Redis connection lost");
     * }
     * ```
     */
    getHealth(): CacheHealth;
    /**
     * Memoizes a function with intelligent caching
     *
     * This method implements memoization - caching function results based on their inputs.
     * It simplifies the common pattern of:
     * 1. Generate a cache key from function parameters
     * 2. Check if result exists in cache
     * 3. If not, execute the function and cache the result
     * 4. Return the cached or computed result
     *
     * @param keyGenerator - Function that generates a cache key from the parameters
     * @param computeFunction - Function to execute if cache miss occurs
     * @param options - Optional caching options
     * @returns A memoized version of the function
     *
     * @example
     * ```typescript
     * import { Hash } from "xypriss-security";
     *
     * // Simple memoization with automatic key generation
     * const memoizedSum = cache.memoize(
     *   (a: number, b: number) => Hash.create(String(a + b)).toString("hex"),
     *   (a: number, b: number) => a + b,
     *   { ttl: 3600 }
     * );
     *
     * const result = await memoizedSum(1, 2); // Computes and caches
     * const cached = await memoizedSum(1, 2); // Returns from cache
     *
     * // Advanced usage with async function
     * const fetchUser = cache.memoize(
     *   (userId: string) => `user:${userId}`,
     *   async (userId: string) => {
     *     const response = await fetch(`/api/users/${userId}`);
     *     return response.json();
     *   },
     *   { ttl: 1800, tags: ["users"] }
     * );
     *
     * const user = await fetchUser("123");
     * ```
     */
    memoize<TArgs extends any[], TResult>(keyGenerator: (...args: TArgs) => string, computeFunction: (...args: TArgs) => TResult | Promise<TResult>, options?: CacheSetOptions): (...args: TArgs) => Promise<TResult>;
    /**
     * Deletes a value from the cache - alias for delete
     *
     * @param key - The cache key to delete
     * @returns Promise resolving to true if the key was deleted, false if not found
     *
     * @example
     * ```typescript
     * const deleted = await cache.delete("user:123");
     * if (deleted) {
     *   console.log("User cache cleared");
     * }
     * ```
     */
    del(key: string): Promise<boolean>;
}

/***************************************************************************
 * XyPrissSecurity - Secure Array Types
 *
 * This file contains type definitions for the SecureArray modular architecture
 *
 * @author Nehonix
 * @license MIT
 *
 * Copyright (c) 2025 Nehonix. All rights reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 ***************************************************************************** */

/**
 * @fileoverview XyPrissSecurity Unified Cache System - Enterprise-Grade Caching Solution
 *
 * A comprehensive,  caching solution combining multiple strategies
 * with military-grade security and ultra-fast performance optimization.
 *
 * ## Cache Strategies
 * - **Memory Cache**: Ultra-fast in-process storage with LRU eviction
 * - **File Cache**: Persistent cross-process storage with real disk monitoring
 * - **Hybrid Cache**: Automatic optimization between memory and file storage
 * - **Redis Cache**: Distributed scalable storage (via integrations)
 *
 * ## Security Features
 * - AES-256-GCM encryption for all cached data
 * - PBKDF2 key derivation with automatic key rotation
 * - Tamper-evident storage with integrity verification
 * - Secure key management and access pattern monitoring
 * - Memory-safe operations with automatic cleanup
 *
 * ## Performance Features
 * - Zlib compression for large values (configurable threshold)
 * - LRU eviction with intelligent memory pressure management
 * - Real-time disk space monitoring and automatic cleanup
 * - Atomic file operations for data consistency
 * - Sub-millisecond cache hits with object pooling
 * - Configurable TTL with background expiration cleanup
 *
 * ## Production Features
 * - Comprehensive error handling with graceful degradation
 * - Real-time performance metrics and health monitoring
 * - Configurable naming strategies (flat, hierarchical, dated, direct)
 * - Cross-platform compatibility (Windows, macOS, Linux)
 * - Zero-dependency core with optional integrations
 * - TypeScript support with complete type definitions
 *
 * @example
 * ```typescript
 * // Quick start with default memory cache
 * import { Cache } from "xypriss-security";
 *
 * await Cache.set('user:123', { name: 'John', role: 'admin' }, { ttl: 3600000 });
 * const user = await Cache.get('user:123');
 *
 * // File-based persistent cache
 * import { FileCache } from "xypriss-security";
 *
 * const fileCache = new FileCache({
 *   directory: './cache',
 *   encrypt: true,
 *   compress: true,
 *   maxCacheSize: 1024 * 1024 * 100 // 100MB
 * });
 *
 * await fileCache.set('session:abc', sessionData, { ttl: 86400000 });
 *
 * // Hybrid cache for optimal performance
 * import { createOptimalCache } from "xypriss-security";
 *
 * const hybridCache = createOptimalCache({
 *   type: 'hybrid',
 *   config: { encrypt: true, compress: true }
 * });
 * ```
 *
 * @version 4.2.3
 * @author NEHONIX
 * @since 2024-12-19
 * @license MIT
 */
/**
 * Default secure in-memory cache instance
 *
 * Pre-configured singleton instance with optimal security settings for immediate use.
 * Features AES-256-GCM encryption, LRU eviction, and automatic memory management.
 *
 * @example
 * ```typescript
 * import { Cache } from "xypriss-security";
 *
 * // Store user session with 1-hour TTL
 * await Cache.set('session:user123', {
 *   userId: 123,
 *   permissions: ['read', 'write'],
 *   loginTime: Date.now()
 * }, { ttl: 3600000 });
 *
 * // Retrieve cached data
 * const session = await Cache.get('session:user123');
 *
 * // Check cache statistics
 * const stats = Cache.getStats();
 * console.log(`Hit rate: ${stats.hitRate}%`);
 * ```
 *
 * @since 4.2.2
 */
declare const Cache: SIMC;

/**
 * Generate a secure file path for cache storage
 *
 * Creates secure, collision-resistant file paths using configurable naming strategies.
 * All keys are hashed using SHA-256 to prevent directory traversal attacks and
 * ensure consistent path generation across platforms.
 *
 * @param key - The cache key to generate a path for
 * @param options - Optional configuration for path generation
 * @returns Secure file path for the given key
 *
 * @example
 * ```typescript
 * import { generateFilePath } from "xypriss-security";
 *
 * // Hierarchical structure (recommended for large caches)
 * const path1 = generateFilePath('user:123', {
 *   namingStrategy: 'hierarchical',
 *   directory: './cache'
 * });
 * // Result: ./cache/a1/b2/a1b2c3d4...cache
 *
 * // Date-based organization (good for time-series data)
 * const path2 = generateFilePath('daily-report', {
 *   namingStrategy: 'dated',
 *   directory: './reports'
 * });
 * // Result: ./reports/2024/12/19/hash...cache
 *
 * // Direct naming (human-readable, limited special chars)
 * const path3 = generateFilePath('config-settings', {
 *   namingStrategy: 'direct',
 *   directory: './config'
 * });
 * // Result: ./config/config-settings.cache
 * ```
 *
 * @since 4.2.2
 */
declare const generateFilePath: (key: string, options?: Partial<FileCacheOptions>) => string;
declare const defaultFileCache: FileCache;
/**
 * Write data to file cache with automatic optimization
 *
 * Stores data in the file cache with intelligent compression and encryption.
 * Automatically handles large objects and provides atomic write operations.
 *
 * @param key - Unique identifier for the cached data
 * @param data - Data to cache (any serializable type)
 * @param options - Optional cache configuration
 * @returns Promise resolving to true if successful
 *
 * @example
 * ```typescript
 * import { writeFileCache } from "xypriss-security";
 *
 * // Cache user profile with encryption
 * const success = await writeFileCache('profile:user123', {
 *   name: 'John Doe',
 *   preferences: { theme: 'dark', lang: 'en' }
 * }, {
 *   encrypt: true,
 *   ttl: 3600000 // 1 hour
 * });
 * ```
 *
 * @since 4.2.2
 */
declare const writeFileCache: (key: string, data: CachedData, options?: Partial<FileCacheOptions>) => Promise<boolean>;
/**
 * Read data from file cache with automatic decryption
 *
 * Retrieves and automatically decrypts/decompresses cached data.
 * Returns null for expired or non-existent entries.
 *
 * @param key - Unique identifier for the cached data
 * @returns Promise resolving to cached data or null
 *
 * @example
 * ```typescript
 * import { readFileCache } from "xypriss-security";
 *
 * const userData = await readFileCache('profile:user123');
 * if (userData) {
 *   console.log('Welcome back,', userData.name);
 * } else {
 *   console.log('Cache miss - loading from database');
 * }
 * ```
 *
 * @since 4.2.2
 */
declare const readFileCache: (key: string) => Promise<CachedData | null>;
/**
 * Remove specific entry from file cache
 *
 * Permanently deletes a cache entry and updates disk usage statistics.
 * Safe to call on non-existent keys.
 *
 * @param key - Unique identifier for the cached data
 * @returns Promise resolving to true if entry was deleted
 *
 * @example
 * ```typescript
 * import { removeFileCache } from "xypriss-security";
 *
 * // Remove expired session
 * const removed = await removeFileCache('session:expired123');
 * console.log(removed ? 'Session cleared' : 'Session not found');
 * ```
 *
 * @since 4.2.2
 */
declare const removeFileCache: (key: string) => Promise<boolean>;
/**
 * Check if file cache entry exists and is valid
 *
 * Verifies cache entry existence without loading the data.
 * Automatically removes expired entries during check.
 *
 * @param key - Unique identifier for the cached data
 * @returns Promise resolving to true if entry exists and is valid
 *
 * @example
 * ```typescript
 * import { hasFileCache } from "xypriss-security";
 *
 * if (await hasFileCache('config:app-settings')) {
 *   const config = await readFileCache('config:app-settings');
 * } else {
 *   // Load from default configuration
 * }
 * ```
 *
 * @since 4.2.2
 */
declare const hasFileCache: (key: string) => Promise<boolean>;
/**
 * Clear all file cache entries
 *
 * Removes all cached files and resets statistics.
 * Use with caution in production environments.
 *
 * @example
 * ```typescript
 * import { clearFileCache } from "xypriss-security";
 *
 * // Clear cache during maintenance
 * await clearFileCache();
 * console.log('Cache cleared successfully');
 * ```
 *
 * @since 4.2.2
 */
declare const clearFileCache: () => Promise<void>;
/**
 * Get comprehensive file cache statistics
 *
 * Returns real-time statistics including disk usage, hit rates,
 * and performance metrics with health assessment.
 *
 * @returns Promise resolving to detailed cache statistics
 *
 * @example
 * ```typescript
 * import { getFileCacheStats } from "xypriss-security";
 *
 * const stats = await getFileCacheStats();
 * console.log(`Cache efficiency: ${stats.hitRate}%`);
 * console.log(`Disk usage: ${stats.diskUsage.percentage}%`);
 * console.log(`Average response time: ${stats.avgResponseTime}ms`);
 * ```
 *
 * @since 4.2.2
 */
declare const getFileCacheStats: () => Promise<FileCacheStats>;
/**
 * Clean up expired file cache entries
 *
 * Removes expired entries and optimizes disk usage.
 * Automatically runs in background but can be triggered manually.
 *
 * @param options - Optional cleanup configuration
 * @returns Promise resolving to cleanup results
 *
 * @example
 * ```typescript
 * import { cleanupFileCache } from "xypriss-security";
 *
 * const result = await cleanupFileCache();
 * console.log(`Cleaned ${result.cleaned} files, freed ${result.totalSize} bytes`);
 * ```
 *
 * @since 4.2.2
 */
declare const cleanupFileCache: (options?: Partial<FileCacheCleanupOptions>) => Promise<{
    cleaned: number;
    errors: number;
    totalSize: number;
}>;
/**
 * Read data from memory cache with fallback
 *
 * Retrieves data from the default memory cache instance.
 * Returns empty object if key is not found (legacy behavior).
 *
 * @param args - Arguments passed to Cache.get()
 * @returns Promise resolving to cached data or empty object
 *
 * @example
 * ```typescript
 * import { readCache } from "xypriss-security";
 *
 * const sessionData = await readCache('session:user123');
 * console.log('User ID:', sessionData.userId || 'Not found');
 * ```
 *
 * @since 4.2.2
 */
declare const readCache: (...args: Parameters<typeof Cache.get>) => Promise<CachedData>;
/**
 * Write data to memory cache
 *
 * Stores data in the default memory cache instance with encryption
 * and automatic compression for large values.
 *
 * @param args - Arguments passed to Cache.set()
 * @returns Promise resolving to true if successful
 *
 * @example
 * ```typescript
 * import { writeCache } from "xypriss-security";
 *
 * await writeCache('user:profile', userData, { ttl: 1800000 }); // 30 min
 * ```
 *
 * @since 4.2.2
 */
declare const writeCache: (...args: Parameters<typeof Cache.set>) => Promise<boolean>;
/**
 * Get memory cache performance statistics
 *
 * Returns comprehensive statistics including hit rates, memory usage,
 * and performance metrics for the default cache instance.
 *
 * @returns Current cache statistics
 *
 * @example
 * ```typescript
 * import { getCacheStats } from "xypriss-security";
 *
 * const stats = getCacheStats();
 * console.log(`Hit rate: ${stats.hitRate}%`);
 * console.log(`Memory usage: ${stats.memoryUsage} bytes`);
 * ```
 *
 * @since 4.2.2
 */
declare const getCacheStats: () => CacheStats;
/**
 * Remove entry from memory cache
 *
 * Immediately removes a cache entry and frees associated memory.
 * Safe to call on non-existent keys.
 *
 * @param key - Cache key to remove
 * @returns Promise that resolves when deletion is complete
 *
 * @example
 * ```typescript
 * import { expireCache } from "xypriss-security";
 *
 * await expireCache('session:expired123');
 * console.log('Session removed from cache');
 * ```
 *
 * @since 4.2.2
 */
declare const expireCache: (key: string) => Promise<void>;
/**
 * Clear all memory cache entries
 *
 * Removes all cached data and resets statistics.
 * Use with caution in production environments.
 *
 * @returns Promise that resolves when cache is cleared
 *
 * @example
 * ```typescript
 * import { clearAllCache } from "xypriss-security";
 *
 * await clearAllCache();
 * console.log('Memory cache cleared');
 * ```
 *
 * @since 4.2.2
 */
declare const clearAllCache: () => Promise<void>;
/**
 * Legacy filepath function
 * @deprecated use generateFilePath instead
 */
declare const filepath: (origin: string) => string;
/**
 * Create optimal cache instance based on performance requirements
 *
 * Factory function that creates the most suitable cache instance for your use case.
 * Automatically configures security settings and performance optimizations.
 *
 * @param options - Cache configuration options
 * @param options.type - Cache strategy: 'memory' (fastest), 'file' (persistent), 'hybrid' (balanced)
 * @param options.config - Optional file cache configuration (ignored for memory-only)
 * @returns Configured cache instance optimized for the specified requirements
 *
 * @example
 * ```typescript
 * import { createOptimalCache } from "xypriss-security";
 *
 * // Ultra-fast memory cache for session data
 * const sessionCache = createOptimalCache({ type: 'memory' });
 *
 * // Persistent file cache for application data
 * const appCache = createOptimalCache({
 *   type: 'file',
 *   config: {
 *     directory: './app-cache',
 *     encrypt: true,
 *     maxCacheSize: 100 * 1024 * 1024 // 100MB
 *   }
 * });
 *
 * // Hybrid cache for optimal performance and persistence
 * const hybridCache = createOptimalCache({
 *   type: 'hybrid',
 *   config: { encrypt: true, compress: true }
 * });
 *
 * // Use hybrid cache (memory-first with file backup)
 * await hybridCache.set('user:123', userData);
 * const user = await hybridCache.get('user:123'); // Served from memory
 * ```
 *
 * @since 4.2.2
 */
declare const createOptimalCache: (options: {
    type: "memory" | "file" | "hybrid";
    config?: Partial<FileCacheOptions>;
}) => SIMC | FileCache | {
    memory: SIMC;
    file: FileCache;
    get(key: string): Promise<CachedData | null>;
    set(key: string, value: CachedData, options?: any): Promise<boolean>;
};
/**
 * Legacy file cache function names for backward compatibility
 * @deprecated Use the new function names for better clarity
 */
declare const deleteFileCache: (key: string) => Promise<boolean>;
/**
 * Cache module version and metadata
 * @since 4.2.0
 */
declare const CACHE_VERSION = "4.2.3";
declare const CACHE_BUILD_DATE = "2025-04-06";
/**
 * Redis configuration options
 */
interface RedisConfig {
    /** Redis server hostname */
    host: string;
    /** Redis server port */
    port: number;
    /** Redis authentication password */
    password?: string;
    /** Redis database number */
    db?: number;
    /** Connection timeout in milliseconds */
    connectTimeout?: number;
    /** Command timeout in milliseconds */
    commandTimeout?: number;
    /** Redis Cluster configuration */
    cluster?: {
        enabled: boolean;
        nodes: Array<{
            host: string;
            port: number;
        }>;
    };
    /** Redis Sentinel configuration */
    sentinel?: {
        enabled: boolean;
        masters: string[];
        sentinels: Array<{
            host: string;
            port: number;
        }>;
    };
}
/**
 * Memory cache configuration options
 */
interface MemoryConfig {
    /** Maximum memory cache size in MB */
    maxSize: number;
    /** Maximum number of cache entries */
    maxEntries: number;
    /** LRU eviction policy settings */
    evictionPolicy?: "lru" | "lfu" | "fifo";
}
/**
 * Security configuration options
 */
interface SecurityConfig {
    /** Enable AES-256-GCM encryption */
    encryption: boolean;
    /** Enable automatic key rotation */
    keyRotation?: boolean;
    /** Custom encryption key (base64 encoded) */
    customKey?: string;
}
/**
 * Monitoring and health check configuration
 */
interface MonitoringConfig {
    /** Enable performance metrics collection */
    enabled: boolean;
    /** Metrics collection interval in milliseconds */
    interval?: number;
    /** Enable health checks */
    healthChecks?: boolean;
}
/**
 * Cache configuration options
 */
interface CacheConfig {
    /** Cache strategy: memory, redis, or hybrid */
    strategy: "memory" | "redis" | "hybrid";
    /** Default TTL in seconds */
    ttl?: number;
    /** Redis configuration (required for redis and hybrid strategies) */
    redis?: RedisConfig;
    /** Memory configuration (required for memory and hybrid strategies) */
    memory?: MemoryConfig;
    /** Security configuration */
    security?: SecurityConfig;
    /** Monitoring configuration */
    monitoring?: MonitoringConfig;
    /** Enable compression */
    compression?: boolean;
}
/**
 * Cache options for set operations
 */
interface CacheSetOptions {
    /** Time to live in seconds */
    ttl?: number;
    /** Array of tags for bulk invalidation */
    tags?: string[];
}
/**
 * Secure cache statistics interface
 */
interface SecureCacheStats {
    memory: {
        hitRate: number;
        missRate: number;
        size: number;
        entries: number;
        maxSize: number;
        maxEntries: number;
    };
    redis?: {
        hitRate: number;
        missRate: number;
        connected: boolean;
        memoryUsage: number;
        keyCount: number;
    };
    operations: {
        total: number;
        gets: number;
        sets: number;
        deletes: number;
        errors: number;
    };
    performance: {
        avgResponseTime: number;
        p95ResponseTime: number;
        p99ResponseTime: number;
    };
}
/**
 * Cache health status interface
 */
interface CacheHealth {
    status: "healthy" | "degraded" | "unhealthy";
    details: {
        redis?: {
            connected: boolean;
            latency?: number;
            error?: string;
        };
        memory?: {
            usage: number;
            available: number;
        };
        errors?: string[];
        lastCheck: Date;
    };
}
/**
 * Fortified function interface for public API to avoid TypeScript issues with private members
 */
interface IFortifiedFunction<T extends any[], R> {
    (...args: T): R;
    getStats(): any;
    getAnalyticsData(): any;
    getOptimizationSuggestions(): any[];
    getPerformanceTrends(): any;
    detectAnomalies(): any[];
    getDetailedMetrics(): any;
    clearCache(): void;
    getCacheStats(): {
        hits: number;
        misses: number;
        size: number;
    };
    warmCache(args: T[]): Promise<void>;
    handleMemoryPressure(level: "low" | "medium" | "high"): void;
    optimizePerformance(): void;
    updateOptions(newOptions: any): void;
    getConfiguration(): any;
}
/**
 * Cache interface for public API to avoid TypeScript issues with private members
 */
interface ICacheAdapter {
    get<T = any>(key: string): Promise<T | null>;
    set<T = any>(key: string, value: T, options?: CacheSetOptions): Promise<boolean>;
    delete(key: string): Promise<boolean>;
    exists(key: string): Promise<boolean>;
    clear(): Promise<void>;
    connect(): Promise<void>;
    disconnect(): Promise<void>;
    getStats(): Promise<SecureCacheStats>;
    mget<T = any>(keys: string[]): Promise<Record<string, T>>;
    mset<T = any>(entries: Record<string, T> | Array<[string, T]>, options?: CacheSetOptions): Promise<boolean>;
    invalidateByTags(tags: string[]): Promise<number>;
    getTTL(key: string): Promise<number>;
    expire(key: string, ttl: number): Promise<boolean>;
    keys(pattern?: string): Promise<string[]>;
    getHealth(): CacheHealth;
    memoize<TArgs extends any[], TResult>(keyGenerator: (...args: TArgs) => string, computeFunction: (...args: TArgs) => TResult | Promise<TResult>, options?: CacheSetOptions): (...args: TArgs) => Promise<TResult>;
}
/**
 * Creates a type-safe fortified function wrapper
 *
 * This function wraps the `func` utility to provide proper TypeScript types
 * for export scenarios, avoiding the "cannot be named" error.
 *
 * @param fn - The function to xypriss
 * @param options - Optional fortification options
 * @returns A type-safe fortified function
 *
 * @example
 * ```typescript
 * import { createTypedFortifiedFunction } from "xypriss-security";
 *
 * const somme = createTypedFortifiedFunction((a: number, b: number): number => {
 *   return a + b;
 * });
 *
 * export const mathOps = { somme }; // ✅ No TypeScript errors
 * ```
 */
declare function createTypedFortifiedFunction<T extends any[], R>(fn: (...args: T) => R, options?: any): IFortifiedFunction<T, R>;

declare const generateSecureToken: typeof XyPrissSecurity.generateSecureToken;

/**
 * ## Crypto Compatibility Layer
 *
 * Direct function exports for easy migration from Node.js crypto module.
 * These functions provide drop-in replacements with enhanced security features.
 */
/**
 * ### Secure Cipher Operations
 *
 * Enhanced cipher creation and management with automatic security hardening.
 * Provides secure alternatives to Node.js crypto.createCipher functions.
 *
 * @example
 * ```typescript
 * import { createSecureCipheriv, createSecureDecipheriv, generateSecureIV } from "xypriss-security";
 *
 * // Create secure cipher with automatic IV generation
 * const key = "your-encryption-key";
 * const iv = generateSecureIV("aes-256-cbc");
 * const cipher = createSecureCipheriv("aes-256-cbc", key, iv);
 *
 * // Encrypt data
 * let encrypted = cipher.update("sensitive data", "utf8", "hex");
 * encrypted += cipher.final("hex");
 *
 * // Decrypt data
 * const decipher = createSecureDecipheriv("aes-256-cbc", key, iv);
 * let decrypted = decipher.update(encrypted, "hex", "utf8");
 * decrypted += decipher.final("utf8");
 * ```
 */
/** Create secure cipher with enhanced security features */
declare const createSecureCipheriv: typeof RandomCrypto.createSecureCipheriv;
/** Create secure decipher with enhanced security features */
declare const createSecureDecipheriv: typeof RandomCrypto.createSecureDecipheriv;
/** Generate cryptographically secure initialization vector */
declare const generateSecureIV: typeof RandomCrypto.generateSecureIV;
/** Generate multiple secure IVs in batch for performance */
declare const generateSecureIVBatch: typeof RandomCrypto.generateSecureIVBatch;
/** Generate secure IV for specific algorithm */
declare const generateSecureIVForAlgorithm: typeof RandomCrypto.generateSecureIVForAlgorithm;
/** Generate multiple secure IVs for specific algorithm */
declare const generateSecureIVBatchForAlgorithm: typeof RandomCrypto.generateSecureIVBatchForAlgorithm;
/** Validate initialization vector format and security */
declare const validateIV: typeof RandomCrypto.validateIV;
/**
 * ### Random Data Generation
 *
 * High-entropy random data generation for cryptographic operations.
 *
 * @example
 * ```typescript
 * import { getRandomBytes, generateSecureUUID } from "xypriss-security";
 *
 * // Generate random bytes
 * const randomData = getRandomBytes(32);
 *
 * // Generate secure UUID
 * const uuid = generateSecureUUID();
 * ```
 */
/** Generate cryptographically secure random bytes */
declare const getRandomBytes: typeof SecureRandom.getRandomBytes;
/** Generate secure UUID with high entropy */
declare const generateSecureUUID: typeof SecureRandom.generateSecureUUID;
/**
 * ### Token Generation
 *
 * Secure token generation for sessions, API keys, and authentication.
 *
 * @example
 * ```typescript
 * import { generateSessionToken } from "xypriss-security";
 *
 * // Generate session token
 * const sessionToken = generateSessionToken(64, "base64url");
 * ```
 */
/** Generate secure session token with configurable encoding */
declare const generateSessionToken: typeof RandomTokens.generateSessionToken;
/**
 * ### Hash Operations
 *
 * Military-grade hashing functions with timing-safe operations and
 * automatic salt generation for maximum security.
 *
 * @example
 * ```typescript
 * import { createSecureHash, createSecureHMAC, verifyHash } from "xypriss-security";
 *
 * // Create secure hash with automatic salt
 * const hash = createSecureHash("data to hash");
 *
 * // Create HMAC with secret key
 * const hmac = createSecureHMAC("sha256", "secret-key", "data");
 *
 * // Verify hash with timing-safe comparison
 * const isValid = verifyHash("original-data", hash);
 * ```
 *
 * @see {@link https://github.com/paulmillr/noble-hashes} Noble Hashes - Modern Crypto Library
 * @see {@link https://nodejs.org/api/crypto.html#cryptocreatehashstring-options} Node.js Hash Functions
 * @see {@link https://tools.ietf.org/html/rfc2104} RFC 2104 - HMAC Specification
 * @see {@link https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf} NIST SHA Standards
 */
/** Create secure hash with automatic salt generation */
declare const createSecureHash: typeof Hash.createSecureHash;
/** Create secure HMAC with timing-safe operations */
declare const createSecureHMAC: typeof HashAlgorithms.createSecureHMAC;
/** Verify hash with constant-time comparison */
declare const verifyHash: typeof Hash.verifyHash;

/**
 * ### Password Manager Quick Access
 *
 * Convenient alias for password manager with default configuration.
 * For production use with custom configuration, use PasswordManager.create()
 * or PasswordManager.getInstance() with specific options.
 *
 * @example
 * ```typescript
 * import { pm } from "xypriss-security";
 *
 * // Quick password operations with default config
 * const hash = await pm.hash("userPassword");
 * const result = await pm.verify("userPassword", hash);
 *
 * // For custom configuration:
 * // const customPM = PasswordManager.create({ memoryCost: 131072 });
 * ```
 *
 * @deprecated Consider using PasswordManager.getInstance() for explicit configuration
 */
declare const pm: PasswordManager;
/**
 * ## Secure Data Structure Factory Functions
 *
 * Convenient factory functions for creating secure data structures with
 * enhanced security features and automatic memory management.
 */
/**
 * ### Create Secure String
 *
 * Creates a secure string instance with automatic memory management,
 * encryption capabilities, and secure cleanup functionality.
 *
 * **Key Features:**
 * - Automatic memory tracking and cleanup
 * - Optional AES-256 encryption for sensitive data
 * - Memory fragmentation protection
 * - Secure wiping on destruction
 * - Event-driven lifecycle management
 *
 * @param value - The initial string value to secure
 * @param options - Configuration options for security level and features
 * @returns A new SecureString instance with enhanced protection
 *
 * @example Basic Usage
 * ```typescript
 * import { fString } from "xypriss-security";
 *
 * // Create basic secure string
 * const password = fString("userPassword123");
 *
 * // Access string value
 * console.log(password.toString());
 *
 * // Secure cleanup
 * password.destroy();
 * ```
 *
 * @example Advanced Configuration
 * ```typescript
 * import { fString } from "xypriss-security";
 *
 * // Maximum security configuration
 * const sensitiveData = fString("credit-card-4532-1234-5678-9012", {
 *     protectionLevel: "maximum",
 *     enableEncryption: true,
 *     enableFragmentation: true,
 *     enableMemoryTracking: true,
 *     autoCleanup: true
 * });
 *
 * // String operations with automatic encryption/decryption
 * sensitiveData.append("-VERIFIED");
 * const masked = sensitiveData.mask(4, 12, "*");
 *
 * // Cryptographic operations
 * const hash = await sensitiveData.hash("SHA-256");
 * const isValid = sensitiveData.equals("other-string", true); // timing-safe
 *
 * // Automatic cleanup when done
 * sensitiveData.destroy();
 * ```
 *
 * @author Seth Eleazar
 * @since 1.0.0
 */
declare function fString(...args: Parameters<typeof createSecureString>): SecureString;
/**
 * ### Create Secure Object
 *
 * Creates a secure object instance with encryption, metadata management,
 * and comprehensive security features for sensitive data storage.
 *
 * **Key Features:**
 * - Automatic encryption for sensitive values
 * - Metadata tracking and management
 * - Event-driven architecture
 * - Secure serialization and deserialization
 * - Memory protection and cleanup
 *
 * @param initialData - The initial data to store in the secure object
 * @param options - Configuration options for encryption and security
 * @returns A new SecureObject instance with enhanced protection
 *
 * @example Basic Usage
 * ```typescript
 * import { fObject } from "xypriss-security";
 *
 * // Create secure object with initial data
 * const userCredentials = fObject({
 *     username: "john_doe",
 *     apiKey: "secret-api-key-12345",
 *     sessionToken: "session-token-abcdef"
 * });
 *
 * // Access and modify data
 * userCredentials.set("lastLogin", new Date().toISOString());
 * const apiKey = userCredentials.get("apiKey");
 *
 * // Secure cleanup
 * userCredentials.destroy();
 * ```
 *
 * @example Advanced Configuration
 * ```typescript
 * import { fObject } from "xypriss-security";
 *
 * // Create with encryption and metadata tracking
 * const secureConfig = fObject({
 *     databaseUrl: "postgresql://user:pass@localhost/db",
 *     encryptionKey: "master-encryption-key-2025",
 *     apiSecrets: {
 *         stripe: "sk_live_...",
 *         aws: "AKIA..."
 *     }
 * }, {
 *     encryptionKey: process.env.OBJECT_ENCRYPTION_KEY,
 *     enableMetadata: true,
 *     autoCleanup: true
 * });
 *
 * // Mark sensitive keys for special handling
 * secureConfig.markSensitive("databaseUrl");
 * secureConfig.markSensitive("encryptionKey");
 * secureConfig.markSensitive("apiSecrets");
 *
 * // Export with encryption
 * const encrypted = secureConfig.serialize({ encrypt: true });
 *
 * // Event handling
 * secureConfig.on("accessed", (key) => {
 *     console.log(`Sensitive key accessed: ${key}`);
 * });
 * ```
 *
 * @author Seth Eleazar
 * @since 1.0.0
 */
declare function fObject<T extends Record<string, any>>(...args: Parameters<typeof createSecureObject<T>>): SecureObject<T>;
/**
 * ### Create Secure Array
 *
 * Creates a military-grade secure array with AES-256-CTR-HMAC encryption,
 * comprehensive security features, and high-performance operations.
 *
 * **Key Features:**
 * - Military-grade AES-256-CTR-HMAC encryption
 * - Real-time security monitoring and analytics
 * - Automatic memory management and cleanup
 * - Snapshot and versioning capabilities
 * - Event-driven architecture
 * - Multiple export formats with integrity verification
 * - Advanced array operations (unique, shuffle, min/max)
 *
 * @param initialData - The initial array data to secure
 * @param options - Configuration options for encryption and security features
 * @returns A new SecureArray instance with military-grade protection
 *
 * @example Basic Usage
 * ```typescript
 * import { fArray } from "xypriss-security";
 *
 * // Create secure array with sensitive data
 * const apiKeys = fArray([
 *     "api-key-production-12345",
 *     "api-key-staging-67890",
 *     "api-key-development-abcdef"
 * ]);
 *
 * // Set encryption key and encrypt all data
 * apiKeys.setEncryptionKey("your-super-secret-key-2025");
 * apiKeys.encryptAll();
 *
 * // Use like regular array - data automatically encrypted/decrypted
 * apiKeys.push("new-api-key-xyz789");
 * const firstKey = apiKeys.get(0); // Automatically decrypted
 * const filtered = apiKeys.filter(key => key.includes("production"));
 *
 * // Secure cleanup
 * apiKeys.destroy();
 * ```
 *
 * @example Advanced Operations
 * ```typescript
 * import { fArray } from "xypriss-security";
 * import { NehoID as ID } from "nehoid";
 *
 * // Create array for high-volume data processing
 * const dataProcessor = fArray([] as string[], {
 *     encryptionKey: process.env.ARRAY_ENCRYPTION_KEY,
 *     enableCompression: true,
 *     maxSize: 100000,
 *     enableEvents: true
 * });
 *
 * // Bulk data processing with automatic encryption
 * const dataTypes = ["user", "transaction", "audit", "system"];
 * const maxRecords = 10000;
 *
 * for (let i = 0; i < maxRecords; i++) {
 *     const randomType = dataTypes[Math.floor(Math.random() * dataTypes.length)];
 *     const record = `${randomType}-record-${i}-${Date.now()}`;
 *     dataProcessor.push(record);
 * }
 *
 * // Advanced analytics and operations
 * const stats = dataProcessor.getStats();
 * const snapshot = dataProcessor.createSnapshot();
 * const exported = dataProcessor.exportData("json");
 *
 * // Event monitoring
 * dataProcessor.on("push", (index, value) => {
 *     console.log(`New record added at index ${index}`);
 * });
 *
 * // Generate probability analysis
 * console.log("Data distribution:", ID.probabilityCloud(dataProcessor.toArray()));
 *
 * // Secure cleanup - wipes all data and destroys array
 * dataProcessor.destroy(); // Cannot be used after this
 * ```
 *
 * @example Real-time Security Monitoring
 * ```typescript
 * import { fArray } from "xypriss-security";
 *
 * // Create array with comprehensive monitoring
 * const secureData = fArray(["sensitive-data-1", "sensitive-data-2"], {
 *     enableRealTimeMonitoring: true,
 *     enableIntegrityChecks: true,
 *     enableAuditLogging: true
 * });
 *
 * // Monitor security status
 * const encryptionStatus = secureData.getEncryptionStatus();
 * console.log(`Algorithm: ${encryptionStatus.algorithm}`);
 * console.log(`Encrypted elements: ${encryptionStatus.encryptedCount}`);
 *
 * // Real-time analytics
 * const analytics = secureData.getAnalytics();
 * console.log(`Performance score: ${analytics.performanceScore}`);
 * console.log(`Security level: ${analytics.securityLevel}`);
 * ```
 *
 * @author Seth Eleazar
 * @license MIT
 * @since 1.0.0
 * @see {@link https://github.com/paulmillr/noble-ciphers} Noble Ciphers - AES Implementation
 * @see {@link https://tools.ietf.org/html/rfc3610} RFC 3610 - Counter with CBC-MAC (CCM)
 * @see {@link https://csrc.nist.gov/publications/detail/sp/800-38a/final} NIST SP 800-38A
 */
declare function fArray<T extends SecureArrayValue = SecureArrayValue>(...args: Parameters<typeof createSecureArray<T>>): SecureArray<T extends string ? string : T extends number ? number : T extends boolean ? boolean : T>;

/**
 * ## Advanced Password Security Functions
 *
 * Military-grade password encryption and verification with pepper support,
 * timing-safe operations, and comprehensive security features.
 */
/**
 * ### Encrypt Password with Pepper
 *
 * Encrypts a password using military-grade security with pepper (secret) application
 * before Argon2ID hashing. This provides maximum protection against rainbow table
 * attacks and database compromise scenarios.
 *
 * **Security Features:**
 * - HMAC-SHA256 pepper application for additional entropy
 * - Argon2ID memory-hard hashing algorithm
 * - Timing-safe operations to prevent side-channel attacks
 * - Configurable memory and time costs for future-proofing
 * - Automatic salt generation for each password
 *
 * **Important Security Notes:**
 * - The PEPPER must be stored securely (environment variables, key management system)
 * - PEPPER should never be stored in the same database as password hashes
 * - Use a cryptographically secure random value for PEPPER generation
 * - Consider key rotation policies for long-term security
 *
 * @param password - The plain text password to encrypt
 * @param PEPPER - A secret pepper value (must be stored securely, not in database)
 * @param options - Advanced hashing configuration options
 * @returns Promise<string> - The peppered and hashed password ready for secure storage
 * @throws {Error} If PEPPER is not provided or invalid
 *
 * @example Basic Usage
 * ```typescript
 * import { encryptSecurePass, Random } from "xypriss-security";
 *
 * // Generate secure pepper (do this once, store securely)
 * const pepper = Random.getRandomBytes(32, "hex");
 * console.log("Store this PEPPER securely:", pepper);
 *
 * // In your application (pepper from environment)
 * const pepper = process.env.PASSWORD_PEPPER;
 * const hashedPassword = await encryptSecurePass("userPassword123", pepper);
 *
 * // Store hashedPassword in database
 * await database.users.update(userId, { passwordHash: hashedPassword });
 * ```
 *
 * @example Advanced Configuration
 * ```typescript
 * import { encryptSecurePass, PasswordAlgorithm } from "xypriss-security";
 *
 * // Maximum security configuration
 * const hashedPassword = await encryptSecurePass("userPassword123", pepper, {
 *     algorithm: PasswordAlgorithm.ARGON2ID,
 *     memoryCost: 131072,    // 128 MB memory usage
 *     timeCost: 4,           // 4 iterations
 *     parallelism: 2,        // 2 parallel threads
 *     hashLength: 64,        // 64-byte output
 *     saltLength: 32         // 32-byte salt
 * });
 * ```
 *
 * @example Production Setup
 * ```typescript
 * // .env file
 * PASSWORD_PEPPER=your-cryptographically-secure-pepper-value-here
 *
 * // Application code
 * import { encryptSecurePass } from "xypriss-security";
 *
 * const pepper = process.env.PASSWORD_PEPPER;
 * if (!pepper) {
 *     throw new Error("PASSWORD_PEPPER environment variable is required");
 * }
 *
 * // User registration
 * const hashedPassword = await encryptSecurePass(userPassword, pepper);
 * await saveUserToDatabase({ email, passwordHash: hashedPassword });
 * ```
 *
 * @security
 * - **HMAC-SHA256**: Applied to password with pepper for additional entropy
 * - **Argon2ID**: Memory-hard algorithm resistant to GPU and ASIC attacks
 * - **Timing Safety**: Constant-time operations prevent timing attacks
 * - **Salt Generation**: Automatic unique salt for each password
 * - **Memory Protection**: Secure memory handling throughout the process
 *
 * @author suppercodercodelover
 * @since 2.0.0
 */
declare function encryptSecurePass(password: string, PEPPER: string, options?: PasswordHashOptions): Promise<string>;
/**
 * ### Verify Encrypted Password
 *
 * Verifies a plain text password against a peppered hash using timing-safe comparison.
 * This function must be used with passwords that were encrypted using encryptSecurePass()
 * to ensure proper pepper application and security verification.
 *
 * **Security Features:**
 * - Constant-time comparison to prevent timing attacks
 * - Same HMAC-SHA256 pepper application as encryption
 * - Resistant to side-channel analysis
 * - No information leakage through execution time
 * - Comprehensive error handling and validation
 *
 * **Important Security Notes:**
 * - Must use the exact same PEPPER value as used in encryptSecurePass()
 * - Verification time is constant regardless of password correctness
 * - Function returns only boolean result to prevent information leakage
 * - All intermediate values are securely cleared from memory
 *
 * @param password - The plain text password to verify
 * @param hashedPassword - The peppered hash from database (created with encryptSecurePass)
 * @param PEPPER - The same secret pepper value used during encryption
 * @returns Promise<boolean> - true if password is valid, false otherwise
 * @throws {Error} If PEPPER is not provided or verification fails
 *
 * @example Basic Login Verification
 * ```typescript
 * import { verifyEncryptedPassword } from "xypriss-security";
 *
 * // User login attempt
 * const pepper = process.env.PASSWORD_PEPPER;
 * const userPassword = "userPassword123";
 * const storedHash = await database.users.getPasswordHash(userId);
 *
 * const isValid = await verifyEncryptedPassword(
 *     userPassword,
 *     storedHash,
 *     pepper
 * );
 *
 * if (isValid) {
 *     // Login successful - create session
 *     const sessionToken = generateSessionToken();
 *     await createUserSession(userId, sessionToken);
 *     console.log("Login successful!");
 * } else {
 *     // Login failed - log attempt and return error
 *     await logFailedLoginAttempt(userId);
 *     console.log("Invalid credentials");
 * }
 * ```
 *
 * @example Production Authentication Flow
 * ```typescript
 * import { verifyEncryptedPassword } from "xypriss-security";
 *
 * async function authenticateUser(email: string, password: string) {
 *     try {
 *         // Get user and password hash from database
 *         const user = await database.users.findByEmail(email);
 *         if (!user) {
 *             // Use timing-safe dummy verification to prevent user enumeration
 *             await verifyEncryptedPassword("dummy", "dummy-hash", pepper);
 *             return { success: false, error: "Invalid credentials" };
 *         }
 *
 *         // Verify password with timing-safe comparison
 *         const pepper = process.env.PASSWORD_PEPPER;
 *         const isValid = await verifyEncryptedPassword(
 *             password,
 *             user.passwordHash,
 *             pepper
 *         );
 *
 *         if (isValid) {
 *             // Update last login timestamp
 *             await database.users.updateLastLogin(user.id);
 *
 *             // Create secure session
 *             const sessionToken = generateSessionToken(64, "base64url");
 *             await database.sessions.create({
 *                 userId: user.id,
 *                 token: sessionToken,
 *                 expiresAt: new Date(Date.now() + 24 * 60 * 60 * 1000) // 24 hours
 *             });
 *
 *             return {
 *                 success: true,
 *                 user: { id: user.id, email: user.email },
 *                 sessionToken
 *             };
 *         } else {
 *             // Log failed attempt for security monitoring
 *             await database.auditLog.create({
 *                 action: "failed_login",
 *                 userId: user.id,
 *                 ip: request.ip,
 *                 timestamp: new Date()
 *             });
 *
 *             return { success: false, error: "Invalid credentials" };
 *         }
 *     } catch (error) {
 *         console.error("Authentication error:", error);
 *         return { success: false, error: "Authentication failed" };
 *     }
 * }
 * ```
 *
 * @example Rate Limiting and Security
 * ```typescript
 * import { verifyEncryptedPassword } from "xypriss-security";
 *
 * async function secureLogin(email: string, password: string, clientIP: string) {
 *     // Check rate limiting first
 *     const attempts = await getFailedAttempts(clientIP);
 *     if (attempts >= 5) {
 *         throw new Error("Too many failed attempts. Please try again later.");
 *     }
 *
 *     // Verify password
 *     const pepper = process.env.PASSWORD_PEPPER;
 *     const user = await getUserByEmail(email);
 *
 *     if (!user) {
 *         // Timing-safe dummy operation
 *         await verifyEncryptedPassword("dummy", "dummy-hash", pepper);
 *         await incrementFailedAttempts(clientIP);
 *         return false;
 *     }
 *
 *     const isValid = await verifyEncryptedPassword(password, user.passwordHash, pepper);
 *
 *     if (isValid) {
 *         await clearFailedAttempts(clientIP);
 *         return true;
 *     } else {
 *         await incrementFailedAttempts(clientIP);
 *         return false;
 *     }
 * }
 * ```
 *
 * @security
 * - **Timing Safety**: Constant execution time prevents timing attacks
 * - **Pepper Consistency**: Uses same HMAC-SHA256 pepper as encryption
 * - **Side-Channel Resistance**: No information leakage through execution patterns
 * - **Memory Protection**: Secure handling of sensitive data throughout verification
 * - **Error Handling**: Comprehensive validation without information disclosure
 *
 * @author suppercodercodelover
 * @since 2.0.0
 */
declare function verifyEncryptedPassword(password: string, hashedPassword: string, PEPPER: string): Promise<boolean>;

export { SecureBuffer as Buffer, CACHE_BUILD_DATE, CACHE_VERSION, Cache, CryptoHandler, CONFIG as DEFAULT_CACHE_CONFIG, DEFAULT_FILE_CACHE_CONFIG, DEFAULT_SENSITIVE_KEYS, EnhancedUint8Array, EntropyPool, EntropyQuality, EntropySource, EventManager, FileCache, FortifiedFunction, Hash, HashAdvanced, HashAlgorithm$2 as HashAlgorithm, HashAlgorithms, HashEntropy, HashSecurity, HashStrength, HashUtils, HashValidator, IdGenerator, KeyDerivationAlgorithm, Keys, LogLevel$1 as LogLevel, MODULE_INFO, MetadataManager, PasswordAlgorithm, PasswordAlgorithms, PasswordBatch, PasswordGenerator, PasswordManager, PasswordMigration, PasswordSecurity, PasswordSecurityLevel, PasswordUtils, RNGState, SecureRandom as Random, RandomCrypto, RandomEntropy, RandomGenerators, RandomSecurity, RandomSources, RandomTokens, SecureCacheClient as SCC, SECURE_OBJECT_VERSION, SecureArray, SecureBuffer, SIMC as SecureInMemoryCache, SecureObject, SecurePasswordManager, SecureRandom, SecureString, SecurityIssueType, SecurityLevel$1 as SecurityLevel, SensitiveKeysManager, SerializationHandler, TamperEvidentLogger, TokenType, UFSIMC as UltraFastSecureInMemoryCache, ValidationUtils, Validators, XyPrissSecurity as XyPriss, XyPrissSecurity, analyzePasswordStrength, argon2Derive, asciiToString, assessRSASecurity, balloonDerive, base32ToBuffer, base58ToBuffer, base64ToBase64Url, base64ToBuffer, base64ToString, base64UrlToBase64, base64UrlToBuffer, base64UrlToString, baseToNumber, benchmarkRSAPerformance, binaryToBuffer, binaryToNumber, bufferToBase32, bufferToBase58, bufferToBase64, bufferToBase64Url, bufferToBinary, bufferToHex, bufferToOctal, bufferToString, bufferToUrlEncoded, buffersEqual, bytesToUint16, bytesToUint32, cacheHarden, calculateRSAKeySize, chunkBuffer, cleanupFileCache, clearAllCache, clearFileCache, cloneSecureObject, commonPassword, compare, concatBuffers, constantTimeEqual, contexts, convertBase, createAttestation, createCanary, createCanaryFunction, createCanaryObject, createFortifiedFunction, createLibraryAttestation, createOptimalCache, createPasswordManager, createReadOnlySecureObject, createSecureCipheriv, createSecureDecipheriv, createSecureHMAC, createSecureHash, createSecureObject, createSecureObjectWithSensitiveKeys, createTypedFortifiedFunction, defaultFileCache, defaultPasswordManager, deleteFileCache, detectContextInjection, detectEncoding, detectInjection, detectSQLInjection, detectXSS, encryptSecurePass, expireCache, fArray, fObject, fString, faultResistantEqual, filepath, formatBytes, func, genSalt, generateAttestationKey, generateFilePath, generateKyberKeyPair, generateProtectedRSAKeyPairForData, generateRSAKeyPairForData, generateSecureIV, generateSecureIVBatch, generateSecureIVBatchForAlgorithm, generateSecureIVForAlgorithm, generateSecurePassword, generateSecureToken, generateSecureUUID, generateSessionToken, getCacheStats, getDefaultPasswordPolicy, getEncryptionSuggestion, getFileCacheStats, getMaxDataSizeForRSAKey, getMilitaryConfig, getRSARecommendations, getRandomBytes, getRecommendedConfig, hasFileCache, hasKeyboardPattern, hash, hashPassword, hexToBuffer, hexToString, isCommonPassword, keyboardPatterns, kyberDecapsulate, kyberEncapsulate, lamportGenerateKeypair, lamportSign, lamportVerify, maskedAccess, migrateBcryptPassword, numberToBase, numberToBinary, numberToOctal, octalToBuffer, octalToNumber, padBuffer, pm, randomBuffer, randomDelay, readCache, readFileCache, removeFileCache, reverseBytes, ringLweDecrypt, ringLweEncrypt, ringLweGenerateKeypair, secureDeserialize, secureModPow, secureSerialize, secureWipe, simpleChecksum, sqlPatterns, stringToAscii, stringToBase64, stringToBase64Url, stringToBuffer, stringToHex, testRSAWithDataSize, triggerCanary, uint16ToBytes, uint32ToBytes, urlDecode, urlEncode, validateDataSizeForRSAKey, validateIV, validateRSAKeyPair, verifyAttestation, verifyEncryptedPassword, verifyHash, verifyLibraryAttestation, verifyPassword, verifyRuntimeSecurity, writeCache, writeFileCache, xorBuffers, xssPatterns };
export type { APIKeyOptions, AgilityHashOptions, AlgorithmConfig, AllRandomTypes, AttestationOptions, AttestationResult, AuditEntry, CacheConfig, CacheEntry, CacheHealth, CacheOptions, CacheSetOptions, CacheStats, CachedData, CanaryOptions, CipherConfig, ComparisonResult, CryptoStats, CryptoUtilityOptions, DeserializationOptions, DeserializationResult, ElementMetadata, EncodingHashType, EncodingType, EntropyAnalysisResult$1 as EntropyAnalysisResult, EntropyCollector, EntropyOptions, EntropySourceConfig, EntropySourceFunction, EventListener, ExecutionEvent, FileCacheCleanupOptions, FileCacheMetadata, FileCacheOptions, FileCacheStats, FileCacheStrategy, FlexibleSecureArray, ForgeInterface, FortifiedFunctionOptions, FunctionStats, HSMHashOptions, HSMIntegrityResult, HashAgilityResult, HashBasedSignatureOptions, HashConfiguration, HashEntropyAnalysis, HashMonitoringResult, HashOperationData, HashOptions, HashSecurityLevel, ICacheAdapter, IFortifiedFunction, IVGenerationOptions, KeyDerivationOptions, KeyPair, LibraryStatus, LogEntry, LogVerificationResult, MemoryConfig, MemoryHardOptions, MemoryHardResult, MemoryUsage, MiddlewareOptions, MonitoringConfig, NobleHashesInterface, PasswordAuditResult, PasswordGenerationOptions, PasswordGenerationResult, PasswordHashMetadata, PasswordHashOptions, PasswordManagerConfig, PasswordMigrationResult, PasswordPolicy, PasswordStorageOptions, PasswordStrengthAnalysis, PasswordStrengthResult, PasswordValidationResult, PasswordVerificationResult, PostQuantumDecapsulation, PostQuantumEncapsulation, PostQuantumKeyPair, PostQuantumParams, QuantumSafeOptions$1 as QuantumSafeOptions, RandomBytesInterface, RandomGenerationOptions, RandomOptions, RandomState, RedisConfig, SearchOptions, SecureArrayEvent, SecureArrayEventListener, SecureArrayOptions, SecureArraySerializationOptions, SecureArrayStats, SecureArrayValue, SecureCacheStats, SecureExecutionContext, SecureObjectData, SecureObjectEvent, SecureObjectOptions, SecureRandomInterface, SecureStringEvent, SecureStringEventListener, SecureStringOptions, SecureTokenOptions, SecureValue, SecurityCheck, SecurityConfig, SecurityFlags, SecurityIssue, SecurityMonitoringResult, SecurityTestResult, SecurityValidator, SecurityVerificationOptions, SecurityVerificationResult, SerializationOptions$1 as SerializationOptions, SerializationResult, SessionTokenOptions, SideChannelOptions, SodiumInterface, SplitOptions, StrengthConfiguration, StringStatistics, TokenGenerationOptions, TweetNaClInterface, UltraCacheOptions, UltraMemoryCacheEntry, UltraStats, ValidationResult, ValueMetadata, VerificationOptions };
