nehoid
Version:
Advanced unique ID generation utility with multi-layer encoding, collision detection, and context-aware features
1,521 lines (1,513 loc) • 53.6 kB
TypeScript
/**
* Supported encoding types for data transformation.
*
* These encoding schemes provide various methods for transforming strings,
* including standard encodings, cryptographic preparations, and specialized formats.
* Each type corresponds to a specific encoding algorithm with different properties
* such as reversibility, URL-safety, and security characteristics.
*/
type ENC_TYPE = "percentEncoding" | "doublepercent" | "base64" | "hex" | "unicode" | "htmlEntity" | "punycode" | "asciihex" | "asciioct" | "rot13" | "base32" | "urlSafeBase64" | "jsEscape" | "cssEscape" | "utf7" | "quotedPrintable" | "decimalHtmlEntity" | "rawHexadecimal" | "jwt" | "url" | "rawHex";
/**
* Core encoding utilities for data transformation and compression.
*
* The Encoder class provides a comprehensive set of encoding and decoding methods
* supporting multiple algorithms including base64, hex, ROT13, compression schemes,
* and specialized encodings. It serves as the foundation for NehoID's transformation
* capabilities and supports both synchronous and asynchronous operations.
*
* @example
* ```typescript
* // Basic encoding and decoding
* const encoded = await Encoder.encode('hello world', 'base64');
* const decoded = Encoder.decode(encoded, 'base64');
*
* // Multiple encodings in sequence
* const multiEncoded = await Encoder.encode('data', ['base64', 'hex']);
* const multiDecoded = Encoder.decode(multiEncoded, ['hex', 'base64']);
*
* // Compression
* const compressed = Encoder.compress('long text to compress', 'gzip');
* const decompressed = Encoder.decompress(compressed, 'gzip');
* ```
*/
declare class Encoder {
/**
* Encode a string using one or more encoding schemes asynchronously.
*
* Applies encoding transformations in sequence, where each encoding
* is applied to the result of the previous encoding. This allows for
* complex encoding pipelines to be built programmatically.
*
* @param input - The string to encode
* @param encodings - Single encoding type or array of encoding types to apply in sequence
* @returns Promise that resolves to the encoded string
*
* @example
* ```typescript
* // Single encoding
* const base64Result = await Encoder.encode('hello', 'base64');
* // Output: 'aGVsbG8='
*
* // Multiple encodings
* const result = await Encoder.encode('data', ['base64', 'hex']);
* // Applies base64 first, then hex to the result
*
* // URL-safe encoding
* const urlSafe = await Encoder.encode('user input', 'urlSafeBase64');
* ```
*/
static encode(input: string, encodings: ENC_TYPE | ENC_TYPE[]): Promise<string>;
/**
* Decode a string using one or more decoding schemes.
*
* Reverses encoding transformations by applying decodings in reverse order.
* Supports both manual specification of decoding types and automatic detection.
*
* @param input - The encoded string to decode
* @param encodings - Single decoding type or array of decoding types to apply in reverse order
* @param opt - Optional decoding configuration
* @param opt.autoDetect - Whether to attempt automatic encoding detection (experimental)
* @returns The decoded string
*
* @example
* ```typescript
* // Single decoding
* const original = Encoder.decode('aGVsbG8=', 'base64');
* // Output: 'hello'
*
* // Multiple decodings (reverse order)
* const result = Encoder.decode(encodedData, ['hex', 'base64']);
* // Decodes hex first, then base64
*
* // With auto-detection
* const decoded = Encoder.decode(encodedStr, 'base64', { autoDetect: true });
* ```
*/
static decode(input: string, encodings: ENC_TYPE | ENC_TYPE[], opt?: {
autoDetect?: boolean;
}): string;
/**
* Compress a string using LZ77 or GZIP-style compression.
*
* Reduces the size of input strings using dictionary-based compression algorithms.
* LZ77 uses sliding window compression, while GZIP uses LZW-style dictionary compression.
* Both methods are lossless and can be reversed using the decompress method.
*
* @param input - The string to compress
* @param method - Compression algorithm to use ('lz77' or 'gzip')
* @returns The compressed and base64-encoded string
*
* @example
* ```typescript
* // LZ77 compression (good for repetitive data)
* const compressed = Encoder.compress('abababababab', 'lz77');
* const decompressed = Encoder.decompress(compressed, 'lz77');
*
* // GZIP compression (good for large texts)
* const text = 'A very long string with lots of repetition and patterns...';
* const gzipped = Encoder.compress(text, 'gzip');
* const original = Encoder.decompress(gzipped, 'gzip');
*
* // Measure compression ratio
* const ratio = gzipped.length / text.length;
* console.log(`Compression ratio: ${ratio.toFixed(2)}`);
* ```
*/
static compress(input: string, method: "lz77" | "gzip"): string;
/**
* Decompress a string that was compressed using the compress method.
*
* Reverses the compression applied by the compress method, restoring the
* original string. Supports both LZ77 and GZIP decompression algorithms.
*
* @param input - The compressed string to decompress
* @param method - Decompression algorithm to use ('lz77' or 'gzip')
* @returns The decompressed original string
*
* @example
* ```typescript
* // Round-trip compression
* const original = 'This is a long string with repetitive patterns...';
* const compressed = Encoder.compress(original, 'lz77');
* const decompressed = Encoder.decompress(compressed, 'lz77');
* // decompressed === original
*
* // Error handling
* try {
* const result = Encoder.decompress('invalid-compressed-data', 'gzip');
* } catch (error) {
* console.error('Decompression failed:', error);
* }
*
* // Check decompression success
* const result = Encoder.decompress(compressedData, 'lz77');
* if (!result) {
* console.error('Decompression returned empty result');
* }
* ```
*/
static decompress(input: string, method: "lz77" | "gzip"): string;
}
/**
* Advanced encoding pipeline for processing and transforming IDs.
*
* The EncodingPipeline provides a fluent interface for building complex encoding workflows
* that can combine multiple encoding schemes, compression, and metadata preservation.
* It supports both forward encoding and reverse decoding operations, making it ideal
* for secure ID transformations and data serialization.
*
* @example
* ```typescript
* // Basic encoding pipeline
* const pipeline = new EncodingPipeline()
* .addEncoder('base64')
* .addEncoder('urlSafeBase64')
* .addCompression('gzip');
*
* const encoded = pipeline.process('my-sensitive-id');
*
* // Reverse the encoding
* const original = pipeline.reverse(encoded);
* ```
*
* @example
* ```typescript
* // Complex pipeline with metadata
* const securePipeline = new EncodingPipeline()
* .addEncoders(['base64', 'hex', 'rot13'])
* .addCompression('lz77')
* .enableReversibility()
* .addMetadata('version', '1.0')
* .addMetadata('timestamp', Date.now());
*
* const result = securePipeline.process('user-data-123');
* console.log('Config:', securePipeline.getConfig());
* ```
*/
declare class EncodingPipeline {
private encoders;
private compressionMethod;
private isReversible;
private metadata;
/**
* Add a single encoder to the pipeline.
*
* Encoders are applied in the order they are added. Each encoder transforms
* the output of the previous step in the pipeline.
*
* @param encoder - The encoding type to add to the pipeline
* @returns The pipeline instance for method chaining
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoder('base64')
* .addEncoder('urlSafeBase64');
* ```
*/
addEncoder(encoder: ENC_TYPE): EncodingPipeline;
/**
* Add multiple encoders to the pipeline at once.
*
* This is more efficient than calling addEncoder multiple times
* and maintains the order of the encoders array.
*
* @param encoders - Array of encoding types to add
* @returns The pipeline instance for method chaining
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoders(['base64', 'hex', 'rot13']);
* ```
*/
addEncoders(encoders: ENC_TYPE[]): EncodingPipeline;
/**
* Add compression to the pipeline.
*
* Compression is applied after all encoders and can significantly reduce
* the size of the encoded output. Supports LZ77 and GZIP-style compression.
*
* @param method - The compression method to use ('lz77' or 'gzip')
* @returns The pipeline instance for method chaining
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoder('base64')
* .addCompression('lz77');
* ```
*/
addCompression(method: "lz77" | "gzip"): EncodingPipeline;
/**
* Enable reversibility for the pipeline.
*
* When enabled, the pipeline stores its configuration as metadata
* in the encoded output, allowing for automatic reversal using the reverse() method.
*
* @returns The pipeline instance for method chaining
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoder('base64')
* .enableReversibility();
*
* const encoded = pipeline.process('data');
* const decoded = pipeline.reverse(encoded); // Works automatically
* ```
*/
enableReversibility(): EncodingPipeline;
/**
* Disable reversibility for the pipeline.
*
* When disabled, the pipeline configuration is not stored,
* making the output more compact but irreversible.
*
* @returns The pipeline instance for method chaining
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoder('base64')
* .disableReversibility(); // Explicitly disable
* ```
*/
disableReversibility(): EncodingPipeline;
/**
* Add custom metadata to the pipeline.
*
* Metadata is preserved in reversible pipelines and can be used
* for versioning, debugging, or additional context information.
*
* @param key - The metadata key
* @param value - The metadata value (can be any serializable type)
* @returns The pipeline instance for method chaining
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addMetadata('version', '2.1.0')
* .addMetadata('created', new Date().toISOString())
* .addMetadata('environment', 'production');
* ```
*/
addMetadata(key: string, value: any): EncodingPipeline;
/**
* Process input through the complete encoding pipeline.
*
* Applies all configured encoders, compression, and metadata in sequence.
* If reversibility is enabled, the pipeline configuration is prepended to the output.
*
* @param input - The string to process through the pipeline
* @returns The fully encoded and processed string
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoders(['base64', 'hex'])
* .addCompression('gzip')
* .enableReversibility();
*
* const result = pipeline.process('sensitive-data');
* // Result includes encoded data + pipeline config for reversal
* ```
*/
process(input: string): string;
/**
* Reverse the pipeline processing to recover original input.
*
* Only works if the pipeline was configured with reversibility enabled.
* Automatically extracts the pipeline configuration from the encoded string
* and applies reverse transformations in the correct order.
*
* @param input - The encoded string to reverse
* @returns The original input string, or null if reversal is not possible
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoder('base64')
* .enableReversibility();
*
* const encoded = pipeline.process('my-data');
* const original = pipeline.reverse(encoded);
* // original === 'my-data'
* ```
*
* @example
* ```typescript
* // Error handling
* const result = pipeline.reverse('invalid-encoded-string');
* if (result === null) {
* console.error('Could not reverse the encoding');
* }
* ```
*/
reverse(input: string): string | null;
/**
* Get the current pipeline configuration.
*
* Returns a snapshot of all pipeline settings including encoders,
* compression method, reversibility flag, and metadata.
*
* @returns Configuration object containing all pipeline settings
*
* @example
* ```typescript
* const pipeline = new EncodingPipeline()
* .addEncoder('base64')
* .addCompression('gzip')
* .addMetadata('version', '1.0');
*
* const config = pipeline.getConfig();
* console.log(config);
* // {
* // encoders: ['base64'],
* // compression: 'gzip',
* // reversible: false,
* // metadata: { version: '1.0' }
* // }
* ```
*/
getConfig(): {
encoders: ENC_TYPE[];
compression: "none" | "lz77" | "gzip";
reversible: boolean;
metadata: Record<string, any>;
};
}
/**
* Database ORM integrations for NehoID
* Provides adapters for popular ORMs and database libraries
*/
/**
* Options for ID field generation
*/
interface IdFieldOptions {
/** Prefix to add to the ID */
prefix?: string;
/** ID format to use */
format?: 'standard' | 'uuid' | 'short' | 'nano' | 'semantic';
/** Whether to ensure uniqueness in the database */
ensureUnique?: boolean;
/** Custom ID generator function */
generator?: () => string;
/** Additional options for semantic IDs */
semantic?: {
region?: string;
department?: string;
year?: number;
customSegments?: Record<string, string | number>;
};
}
/**
* Generate a default ID field for Mongoose schemas
* @param options ID field options
* @returns Mongoose schema field definition
*/
declare function mongooseField(options?: IdFieldOptions): {
type: StringConstructor;
default: () => string;
unique: boolean;
required: boolean;
index: boolean;
};
/**
* Generate a default ID field for Sequelize models
* @param options ID field options
* @returns Sequelize model field definition
*/
declare function sequelizeField(options?: IdFieldOptions): {
type: string;
primaryKey: boolean;
defaultValue: () => string;
unique: boolean;
};
/**
* Generate a default ID field for TypeORM entities
* @param options ID field options
* @returns TypeORM decorator factory
*/
declare function typeormDecorator(options?: IdFieldOptions): () => (target: any, propertyKey: string) => void;
/**
* Configuration options for ID generation.
*
* Defines parameters that control how IDs are generated, including size,
* encoding schemes, prefixes, and various generation features.
*/
interface IdGeneratorOptions {
/** The desired length of the generated ID */
size?: number;
/** Number of segments in the ID (for multi-part IDs) */
segments?: number;
/** Separator character between ID segments */
separator?: string;
/** Encoding type(s) to use for the ID */
encoding?: ENC_TYPE | ENC_TYPE[];
/** Prefix to prepend to the generated ID */
prefix?: string;
/** Whether to include a timestamp in the ID */
includeTimestamp?: boolean;
/** Custom alphabet for encoding (overrides default) */
alphabet?: string;
/** Compression algorithm to apply ('none' | 'lz77' | 'gzip') */
compression?: 'none' | 'lz77' | 'gzip';
/** Whether the encoding should be reversible */
reversible?: boolean;
/** Preset format shortcuts ('uuid' | 'nanoid' | 'cuid' | 'ksuid' | 'xid' | 'pushid') */
format?: 'uuid' | 'nanoid' | 'cuid' | 'ksuid' | 'xid' | 'pushid';
/** Case transformation ('lower' | 'upper' | 'mixed' | 'camel' | 'pascal' | 'snake') */
case?: 'lower' | 'upper' | 'mixed' | 'camel' | 'pascal' | 'snake';
/** Character restrictions */
charset?: {
/** Include numbers (0-9) */
numbers?: boolean;
/** Include lowercase letters (a-z) */
lowercase?: boolean;
/** Include uppercase letters (A-Z) */
uppercase?: boolean;
/** Include special characters */
special?: boolean;
/** Exclude specific characters */
exclude?: string[];
};
/** Randomness level ('fast' | 'crypto' | 'secure') */
randomness?: 'fast' | 'crypto' | 'secure';
/** Include expiration timestamp (TTL in milliseconds) */
expiresIn?: number;
/** Include version number in the ID */
version?: number | string;
/** Domain or context identifier for namespacing */
domain?: string;
/** Include checksum for validation */
includeChecksum?: boolean;
/** Pattern template (e.g., 'XXX-XXX-XXXX', 'AA-9999') */
pattern?: string;
/** Sequential numbering within a context */
sequential?: {
/** Context identifier for sequential numbering */
context: string;
/** Starting number (default: 1) */
start?: number;
/** Padding length for numbers */
padLength?: number;
};
/** Custom metadata to embed */
metadata?: Record<string, any>;
/** Quality requirements */
quality?: {
/** Minimum entropy level required ('low' | 'medium' | 'high') */
minEntropy?: 'low' | 'medium' | 'high';
/** Avoid common patterns or sequences */
avoidPatterns?: boolean;
/** Ensure URL-safe characters only */
urlSafe?: boolean;
};
}
/**
* Configuration for collision-resistant ID generation strategies.
*
* Defines how to handle ID collisions during generation, including
* retry limits, backoff strategies, and validation functions.
*/
interface CollisionStrategy {
/** Unique name for this collision strategy */
name: string;
/** Maximum number of generation attempts before failing */
maxAttempts: number;
/** Backoff strategy for retry delays ('linear' | 'exponential') */
backoffType: 'linear' | 'exponential';
/** Function to validate uniqueness of generated IDs */
checkFunction: (id: string) => Promise<boolean>;
}
/**
* Options for generating contextual IDs that incorporate environment data.
*
* Allows IDs to include contextual information such as device details,
* timezone, browser information, and user behavior patterns.
*/
interface ContextOptions {
/** Include device fingerprint in the ID */
includeDevice?: boolean;
/** Include timezone information */
includeTimezone?: boolean;
/** Include browser/user agent details */
includeBrowser?: boolean;
/** Include screen resolution and display info */
includeScreen?: boolean;
/** Include geolocation data (privacy-considerate) */
includeLocation?: boolean;
/** Custom user behavior context string */
userBehavior?: string;
}
/**
* Configuration for semantic ID generation with meaningful segments.
*
* Enables creation of IDs with structured, readable components that
* convey business meaning while maintaining uniqueness.
*/
interface SemanticOptions {
/** Base prefix for the semantic ID */
prefix?: string;
/** Geographic region identifier */
region?: string;
/** Department or organizational unit */
department?: string;
/** Year component for temporal organization */
year?: number;
/** Additional custom segments as key-value pairs */
customSegments?: Record<string, string | number>;
}
/**
* Options for batch ID generation operations.
*
* Controls parameters for generating multiple IDs simultaneously,
* including count, format preferences, and performance optimizations.
*/
interface BatchOptions {
/** Number of IDs to generate */
count: number;
/** Preferred ID format ('standard' | 'nano' | 'short' | 'uuid') */
format?: 'standard' | 'nano' | 'short' | 'uuid';
/** Enable parallel generation for better performance */
parallel?: boolean;
/** Ensure all generated IDs are unique within the batch */
ensureUnique?: boolean;
}
/**
* Configuration options for ID validation operations.
*
* Controls what aspects of an ID to validate, including format checking,
* collision detection, and automatic repair capabilities.
*/
interface ValidationOptions {
/** Validate ID format and structure */
checkFormat?: boolean;
/** Check for collisions with existing IDs */
checkCollisions?: boolean;
/** Attempt to repair corrupted IDs */
repairCorrupted?: boolean;
}
/**
* Health score object for comprehensive ID analysis.
*
* Provides detailed assessment of ID quality including entropy levels,
* predictability analysis, and actionable improvement recommendations.
*/
interface HealthScore {
/** Overall health score (0.0 to 1.0, higher is better) */
score: number;
/** Entropy level assessment ('low' | 'medium' | 'high') */
entropy: 'low' | 'medium' | 'high';
/** Predictability assessment ('low' | 'medium' | 'high') */
predictability: 'low' | 'medium' | 'high';
/** Array of recommendations for improving ID quality */
recommendations: string[];
}
/**
* Statistics object for monitoring ID generation performance.
*
* Tracks various metrics related to ID generation operations,
* including counts, timing, memory usage, and distribution quality.
*/
interface Stats {
/** Total number of IDs generated */
generated: number;
/** Number of collision incidents encountered */
collisions: number;
/** Average time taken for ID generation (formatted string) */
averageGenerationTime: string;
/** Current memory usage of the ID generation system */
memoryUsage: string;
/** Quality score of ID distribution (0.0 to 1.0) */
distributionScore: number;
}
/**
* Configuration for migrating IDs between different formats.
*
* Defines parameters for converting existing IDs from one format to another,
* including batch processing options and migration scope.
*/
interface MigrationOptions {
/** Source format to migrate from */
from: string;
/** Target format to migrate to */
to: string;
/** Preserve chronological ordering during migration */
preserveOrder?: boolean;
/** Number of IDs to process in each batch */
batchSize?: number;
/** Specific IDs to migrate (overrides count) */
ids?: string[];
/** Number of IDs to migrate if ids not specified */
count?: number;
}
/**
* Compatibility options for cross-platform ID generation.
*
* Ensures generated IDs work consistently across different programming
* languages and platforms with specific requirements.
*/
interface CompatibilityOptions {
/** Target platforms to ensure compatibility with */
platform: ('javascript' | 'python' | 'go')[];
/** Required format for the generated IDs */
format: string;
/** Required length of the generated IDs */
length: number;
}
interface QuantumOptions {
entanglementGroup?: string;
quantumSeed?: string;
coherenceTime?: number;
measurementCollapse?: boolean;
}
interface BioMetricIDOptions {
fingerprint?: string;
voicePrint?: string;
retinalPattern?: string;
keystrokeDynamics?: number[];
mouseMovementPattern?: {
x: number;
y: number;
timestamp: number;
}[];
}
interface MLPredictiveOptions {
userBehaviorVector?: number[];
contextualFeatures?: Record<string, number>;
predictionHorizon?: number;
confidenceThreshold?: number;
}
interface BlockchainIDOptions {
networkId?: string;
consensusType?: "proof-of-work" | "proof-of-stake" | "proof-of-authority";
smartContractAddress?: string;
gasLimit?: number;
}
interface NeuroIDOptions {
brainwavePattern?: number[];
cognitiveLoad?: number;
emotionalState?: "neutral" | "excited" | "focused" | "stressed";
neuralSignature?: string;
}
interface DNASequenceOptions {
geneticMarkers?: string[];
chromosomeSegment?: string;
mutationRate?: number;
generationCount?: number;
}
interface SynapticIDOptions {
neuronPathway?: string;
synapticStrength?: number;
neurotransmitterType?: "dopamine" | "serotonin" | "acetylcholine" | "gaba";
plasticity?: number;
}
/**
* Revolutionary features that set NehoID apart from all other ID generation libraries
* @author NEHONIX
* @since 20/05/2025
*/
declare class NehoIdAdvenced {
private static quantumRegistry;
private static mlModel;
private static blockchainNonce;
private static cosmicData;
/**
* 🌌 QUANTUM-ENTANGLED IDs
* Generate IDs that are quantum mechanically entangled with each other
* When one ID changes state, its entangled partners instantly reflect the change
*/
static quantum(options?: QuantumOptions): string;
/**
* 🧬 BIOMETRIC-BASED IDs
* Generate IDs based on unique biological characteristics
*/
static biometric(options: BioMetricIDOptions): string;
/**
* ML-PREDICTIVE IDs
* IDs that predict future usage patterns and optimize accordingly
*/
static predictive(options?: MLPredictiveOptions): string;
/**
*
* BLOCKCHAIN-VERIFIED IDs
* IDs that are cryptographically verified on a blockchain
*/
static blockchain(options?: BlockchainIDOptions): string;
/**
* NEURO-COGNITIVE IDs
* IDs based on brain activity patterns and cognitive states
*/
static neuroCognitive(options?: NeuroIDOptions): string;
/**
* DNA-SEQUENCE IDs
* IDs based on genetic algorithms and DNA-like structures
*/
static dnaSequence(options?: DNASequenceOptions): string;
/**
* SYNAPTIC-NETWORK IDs
* IDs that mimic neural network synaptic connections
*/
static synaptic(options?: SynapticIDOptions): string;
/**
* PROBABILITY-CLOUD IDs
* IDs that exist in multiple probable states simultaneously
*/
static probabilityCloud(states?: string[]): string[];
/**
* METAMORPHIC IDs
* IDs that change form based on context while maintaining core identity
*/
static metamorphic(baseContext: string): {
getId: (currentContext: string) => string;
getHistory: () => string[];
};
/**
* WAVE-FUNCTION IDs
* IDs based on wave interference patterns
*/
static waveFunction(frequency?: number, amplitude?: number): string;
private static generateQuantumState;
private static createBiometricHash;
private static calculateBiometricStability;
private static generateMLPrediction;
private static generateBlockHash;
private static calculateMerkleRoot;
private static analyzeNeuralPattern;
private static hashCognitiveState;
private static processBrainwaves;
private static generateInitialDNASequence;
private static evolveDNASequence;
private static calculateDNAChecksum;
private static calculateStellarPosition;
private static getCosmicTime;
private static getSolarWindData;
private static generateSynapticPattern;
private static encodeNeurotransmitter;
private static generateWavePattern;
private static calculateWaveInterference;
private static findResonanceFrequency;
private static hashString;
private static calculateVariance;
/**
* CROSS-DIMENSIONAL IDs
* IDs that exist across multiple dimensions and realities
*/
static crossDimensional(dimensions?: string[]): Map<string, string>;
/**
* 🎼 HARMONIC-RESONANCE IDs
* IDs based on musical harmony and acoustic resonance
*/
static harmonicResonance(baseNote?: string, scale?: string): string;
private static generateMusicalScale;
private static calculateHarmonics;
private static findOptimalResonance;
}
/**
* Enhanced NehoID class with advanced features
* Provides additional ID generation capabilities
*/
declare class NehoIDV2 {
/**
* Quantum-entangled ID generation
* Creates IDs that are quantum mechanically linked
*/
static quantum: typeof NehoIdAdvenced.quantum;
/**
* Biometric-based ID generation
* Generate IDs from biological characteristics
*/
static biometric: typeof NehoIdAdvenced.biometric;
/**
* ML-powered predictive IDs
* IDs that adapt based on machine learning predictions
*/
static predictive: typeof NehoIdAdvenced.predictive;
/**
* Blockchain-verified IDs
* Cryptographically secured and verifiable IDs
*/
static blockchain: typeof NehoIdAdvenced.blockchain;
/**
* Neuro-cognitive IDs
* Based on brain patterns and cognitive states
*/
static neuroCognitive: typeof NehoIdAdvenced.neuroCognitive;
/**
* DNA-sequence IDs
* Genetic algorithm-based evolution
*/
static dnaSequence: typeof NehoIdAdvenced.dnaSequence;
/**
* Synaptic network IDs
* Mimicking neural synaptic connections
*/
static synaptic: typeof NehoIdAdvenced.synaptic;
/**
* Probability cloud IDs
* Multiple probable states simultaneously
*/
static probabilityCloud: typeof NehoIdAdvenced.probabilityCloud;
/**
* Metamorphic IDs
* Context-aware shape-shifting identities
*/
static metamorphic: typeof NehoIdAdvenced.metamorphic;
/**
* Wave function IDs
* Based on wave interference patterns
*/
static waveFunction: typeof NehoIdAdvenced.waveFunction;
/**
* Cross-dimensional IDs
* Existing across multiple realities
*/
static crossDimensional: typeof NehoIdAdvenced.crossDimensional;
/**
* Harmonic resonance IDs
* Based on musical harmony and acoustics
*/
static harmonicResonance: typeof NehoIdAdvenced.harmonicResonance;
/**
* ADVANCED COMBO METHODS
* These combine multiple advanced features for enhanced uniqueness
*/
/**
* Ultimate ID: Combines quantum, biometric, and ML features
*/
static ultimate(options?: {
quantumGroup?: string;
biometricData?: any;
mlFeatures?: number[];
}): string;
/**
* Neuro-harmonic ID: Combines brain patterns with musical harmony
*/
static neuroHarmonic(emotionalState?: string, baseNote?: string): string;
/**
* ADAPTIVE ID SYSTEM
* IDs that evolve and adapt over time
*/
static createAdaptiveSystem(baseConfig: any): {
generateNext: (context?: string) => string;
getEvolutionHistory: () => string[];
getContextMemory: () => Map<string, number>;
reset: () => void;
};
/**
* FLUID ID POOLS
* Create pools of IDs that flow and transform
*/
static createFluidPool(size?: number): {
draw: () => string | null;
replenish: (count?: number) => void;
getTransformationHistory: (originalId: string) => string[];
poolSize: () => number;
};
private static transformFluidId;
/**
* PREDICTIVE IDS
* IDs that anticipate future states based on time-series data
*/
static predictiveSequence(sequenceLength?: number): {
baseId: string;
sequenceIds: string[];
materialize: (index: number) => string;
};
/**
* UNIVERSAL ID TRANSLATOR
* Translate IDs between different formats and systems
*/
static universalTranslator(id: string, fromUniverse: string, toUniverse: string): string;
private static calculateUniversalConstant;
private static applyTransformation;
/**
* PATTERN-EMBEDDED IDs
* IDs that contain embedded pattern recognition
*/
static patternEmbedded(inputPattern?: string): string;
private static hashPattern;
private static calculatePatternComplexity;
private static generateReference;
/**
* RECURSIVE IDs
* IDs that contain nested versions of themselves
*/
static recursive(depth?: number): string;
/**
* FRACTAL IDs
* IDs with self-similar patterns at different scales
*/
static fractal(iterations?: number, complexity?: number): string;
/**
* OUTCOME-BOUND IDs
* IDs that are bound to a specific outcome
*/
static destinyBound(outcome: string): {
id: string;
manifestDestiny: () => string;
alterFate: (newOutcome: string) => string;
};
private static hashString;
}
/**
* The main NehoID class providing comprehensive ID generation, validation, and management capabilities.
*
* This class offers both simple and advanced ID generation methods, collision-resistant options,
* monitoring tools, and compatibility with various platforms and databases. The generate method
* provides extensive customization including preset formats (UUID, NanoID, CUID, etc.), character
* set control, case transformations, quality requirements, expiration timestamps, versioning,
* sequential numbering, pattern-based generation, and metadata embedding.
*
* @example
* ```typescript
* // Basic ID generation
* const id = NehoID.generate();
*
* // Preset formats
* const uuid = NehoID.generate({ format: 'uuid' });
* const nanoid = NehoID.generate({ format: 'nanoid' });
*
* // Advanced customization
* const customId = NehoID.generate({
* size: 16,
* prefix: 'user-',
* case: 'lower',
* charset: { numbers: true, lowercase: true },
* includeTimestamp: true,
* expiresIn: 24 * 60 * 60 * 1000,
* version: 'v2'
* });
*
* // Collision-safe generation
* const safeId = await NehoID.safe({
* name: 'user-check',
* maxAttempts: 100,
* backoffType: 'exponential',
* checkFunction: async (id) => !await userExists(id)
* });
*
* // Batch generation
* const ids = NehoID.batch({ count: 10, format: 'uuid' });
*
* // Validation
* const isValid = NehoID.validate(id);
*
* // Monitoring
* NehoID.startMonitoring();
* const stats = NehoID.getStats();
* ```
*/
declare class NehoID extends NehoIDV2 {
/**
* Generates a unique ID with optional configuration.
*
* This method provides extensive customization options for ID generation,
* including preset formats, character sets, case transformations, quality requirements,
* and advanced features like expiration, versioning, and sequential numbering.
*
* @param options - Configuration options for ID generation
* @returns A newly generated unique ID string
*
* @example
* ```typescript
* // Basic generation
* const id = NehoID.generate();
*
* // Preset formats
* const uuid = NehoID.generate({ format: 'uuid' });
* const nanoid = NehoID.generate({ format: 'nanoid' });
* const cuid = NehoID.generate({ format: 'cuid' });
*
* // Custom configuration
* const customId = NehoID.generate({
* size: 16,
* prefix: 'user-',
* case: 'lower',
* includeTimestamp: true
* });
* ```
*
* @example
* ```typescript
* // Character set customization
* const numericOnly = NehoID.generate({
* charset: { numbers: true, lowercase: false, uppercase: false },
* size: 10
* });
*
* const urlSafe = NehoID.generate({
* quality: { urlSafe: true },
* charset: { exclude: ['+', '/', '='] }
* });
*
* // Case transformations
* const upperId = NehoID.generate({ case: 'upper' });
* const camelId = NehoID.generate({ case: 'camel' });
* const snakeId = NehoID.generate({ case: 'snake' });
* ```
*
* @example
* ```typescript
* // Advanced features
* const tempId = NehoID.generate({
* expiresIn: 24 * 60 * 60 * 1000, // 24 hours
* version: 'v2',
* domain: 'api',
* includeChecksum: true
* });
*
* // Sequential IDs within contexts
* const orderId = NehoID.generate({
* sequential: { context: 'orders', start: 1000, padLength: 6 }
* });
*
* // Pattern-based generation
* const phoneLike = NehoID.generate({
* pattern: 'XXX-XXX-XXXX' // e.g., ABC-123-4567
* });
*
* const licensePlate = NehoID.generate({
* pattern: 'AA-9999' // e.g., CA-1234
* });
* ```
*
* @example
* ```typescript
* // Quality and security options
* const secureId = NehoID.generate({
* randomness: 'crypto',
* quality: {
* minEntropy: 'high',
* avoidPatterns: true
* },
* size: 32
* });
*
* // Custom metadata embedding
* const taggedId = NehoID.generate({
* metadata: { createdBy: 'api', environment: 'prod' },
* includeTimestamp: true
* });
* ```
*/
static generate(options?: Partial<IdGeneratorOptions>): string;
/**
* Generates an ID from a pattern template.
* @private
*/
private static generateFromPattern;
/**
* Generates a collision-safe ID by checking against a provided validation function.
*
* @param options - Collision strategy configuration including validation function
* @returns A promise that resolves to a collision-free ID string
* @throws Will throw an error if maximum attempts are exceeded without finding a unique ID
*
* @example
* ```typescript
* const safeId = await NehoID.safe({
* name: 'database-check',
* maxAttempts: 50,
* backoffType: 'exponential',
* checkFunction: async (id) => {
* const exists = await db.users.findOne({ id });
* return !exists;
* }
* });
* ```
*/
static safe(options: CollisionStrategy): Promise<string>;
/**
* Generates a standard UUID (Universally Unique Identifier).
*
* @returns A RFC 4122 compliant UUID string
*
* @example
* ```typescript
* const uuid = NehoID.uuid();
* // Output: '550e8400-e29b-41d4-a716-446655440000'
* ```
*/
static uuid(): string;
/**
* Generates a NanoID with configurable length.
*
* @param length - Desired length of the generated ID (default: 21)
* @returns A NanoID string using URL-safe characters
*
* @example
* ```typescript
* const nanoId = NehoID.nanoid(); // Default length 21
* const shortNanoId = NehoID.nanoid(10);
* ```
*/
static nanoid(length?: number): string;
/**
* Generates a short, compact ID.
*
* @param length - Desired length of the generated ID (default: 8)
* @returns A short alphanumeric ID string
*
* @example
* ```typescript
* const shortId = NehoID.short(); // Default length 8
* const customShortId = NehoID.short(12);
* ```
*/
static short(length?: number): string;
/**
* Generates a hexadecimal ID.
*
* @param length - Desired length of the generated ID (default: 16)
* @returns A hexadecimal ID string
*
* @example
* ```typescript
* const hexId = NehoID.hex(); // Default length 16
* const longHexId = NehoID.hex(32);
* ```
*/
static hex(length?: number): string;
/**
* Generates a hierarchical ID with parent-child relationships.
*
* @param options - Configuration options for hierarchical generation
* @returns A hierarchical ID string with encoded relationships
*
* @example
* ```typescript
* const hierarchicalId = NehoID.hierarchical({
* parentId: 'parent-123',
* depth: 2
* });
* ```
*/
static hierarchical(options?: {}): string;
/**
* Generates a time-ordered ID for chronological sorting.
*
* @param options - Configuration options for temporal generation
* @returns A temporal ID string with embedded timestamp
*
* @example
* ```typescript
* const temporalId = NehoID.temporal({
* precision: 'milliseconds',
* includeRandom: true
* });
* ```
*/
static temporal(options?: {}): string;
/**
* Generates a temporal ID from a timestamp.
*
* @param timestamp - Timestamp to convert to temporal ID
* @returns A temporal ID string
*
* @example
* ```typescript
* const temporalId = NehoID.fromTemporal(Date.now());
* ```
*/
static fromTemporal(timestamp: number): string;
/**
* Generates a timestamp from a temporal ID.
*
* @param temporalId - Temporal ID to convert to timestamp
* @returns A timestamp number
*
* @example
* ```typescript
* const timestamp = NehoID.fromTemporalToTimestamp('temporal-123');
* ```
*/
static fromTemporalToTimestamp(temporalId: string): number;
/**
* Generates a sequential ID suitable for database auto-increment replacement.
*
* @param options - Configuration options for sequential generation
* @returns A sequential ID string
*
* @example
* ```typescript
* const sequentialId = NehoID.sequential({
* prefix: 'ORD',
* counter: 1001,
* padLength: 6,
* suffix: true
* });
* // Output: 'ORD001001'
* ```
*/
static sequential(options: {
prefix?: string;
counter: number;
padLength?: number;
suffix?: boolean;
}): string;
/**
* Generates multiple IDs in a batch operation.
*
* @param options - Batch generation configuration
* @returns An array of generated ID strings
*
* @example
* ```typescript
* const ids = NehoID.batch({
* count: 100,
* format: 'uuid',
* parallel: true,
* ensureUnique: true
* });
* ```
*/
static batch(options: BatchOptions): string[];
/**
* Validates an ID against configured rules and formats.
*
* @param id - The ID string to validate
* @param options - Validation configuration options
* @returns True if the ID is valid, false otherwise
*
* @example
* ```typescript
* const isValid = NehoID.validate('user-abc123');
*
* // With options
* const isValidWithCheck = NehoID.validate('user-abc123', {
* checkFormat: true,
* checkCollisions: true
* });
* ```
*/
static validate(id: string, options?: ValidationOptions): boolean;
/**
* Validates multiple IDs in a batch operation.
*
* @param ids - Array of ID strings to validate
* @param options - Validation configuration options
* @returns Array of validation results corresponding to input IDs
*
* @example
* ```typescript
* const results = NehoID.validateBatch(['id1', 'id2', 'id3']);
* // Output: [true, false, true]
* ```
*/
static validateBatch(ids: string[], options?: ValidationOptions): {
valid: string[];
invalid: string[];
duplicates: string[];
};
/**
* Performs a comprehensive health check on an ID.
*
* @param id - The ID string to analyze
* @returns A health score object with entropy, predictability, and recommendations
*
* @example
* ```typescript
* const health = NehoID.healthCheck('user-abc123');
* console.log(health.score); // 0.85
* console.log(health.entropy); // 'high'
* ```
*/
static healthCheck(id: string): HealthScore;
/**
* Starts monitoring ID generation statistics and performance.
*
* @example
* ```typescript
* NehoID.startMonitoring();
* // ... perform operations ...
* const stats = NehoID.getStats();
* ```
*/
static startMonitoring(): void;
/**
* Stops monitoring ID generation statistics.
*
* @example
* ```typescript
* NehoID.stopMonitoring();
* ```
*/
static stopMonitoring(): void;
/**
* Retrieves current monitoring statistics.
*
* @returns A stats object containing generation metrics
*
* @example
* ```typescript
* const stats = NehoID.getStats();
* console.log(`Generated: ${stats.generated}, Collisions: ${stats.collisions}`);
* ```
*/
static getStats(): Stats;
/**
* Generates a contextual ID incorporating environment and user data.
*
* @param options - Contextual generation options
* @returns A contextual ID string
*
* @example
* ```typescript
* const contextualId = NehoID.contextual({
* includeDevice: true,
* includeLocation: true,
* userBehavior: 'login'
* });
* ```
*/
static contextual(options: ContextOptions): string;
/**
* Generates a semantic ID with meaningful segments.
*
* @param options - Semantic generation options
* @returns A semantic ID string
*
* @example
* ```typescript
* const semanticId = NehoID.semantic({
* prefix: 'ORD',
* region: 'US-WEST',
* department: 'SALES',
* year: 2024
* });
* ```
*/
static semantic(options: SemanticOptions): string;
/**
* Migrates IDs from one format to another.
*
* @param options - Migration configuration
* @returns A promise that resolves to an array of migrated ID strings
*
* @example
* ```typescript
* const migratedIds = await NehoID.migrate({
* from: 'uuid',
* to: 'nehoid',
* preserveOrder: true,
* batchSize: 100,
* ids: ['uuid1', 'uuid2']
* });
* ```
*/
static migrate(options: MigrationOptions): Promise<string[]>;
/**
* Generates an ID compatible with specified platforms.
*
* @param options - Compatibility configuration
* @returns A cross-platform compatible ID string
*
* @example
* ```typescript
* const compatibleId = NehoID.compatible({
* platform: ['javascript', 'python'],
* format: 'alphanumeric',
* length: 16
* });
* ```
*/
static compatible(options: CompatibilityOptions): string;
}
/**
* Checksum and hash utilities for NehoID.
*
* This module provides various checksum and hashing algorithms
* for ID validation, integrity checking, and data fingerprinting.
*/
type ChecksumAlgorithm = "djb2" | "crc32" | "adler32" | "fnv1a" | "murmur3";
/**
* Generates checksums using various algorithms.
*
* Provides multiple checksum algorithms for different use cases:
* - djb2: Fast, simple hash (default)
* - crc32: Cyclic redundancy check (good for error detection)
* - adler32: Adler-32 checksum (fast, good for small data)
* - fnv1a: FNV-1a hash (good distribution)
* - murmur3: MurmurHash3 (high quality, good for large data)
*/
declare class Checksum {
private static readonly MAX_INPUT_LENGTH;
private static readonly MIN_CHECKSUM_LENGTH;
private static readonly MAX_CHECKSUM_LENGTH;
private static readonly VALID_ALGORITHMS;
private static crcTableCache;
/**
* Generates a checksum using the specified algorithm.
*
* @param input - String to generate checksum for
* @param algorithm - Checksum algorithm to use (default: 'djb2')
* @param length - Desired length of checksum output (default: 4 for short checksums)
* @returns Checksum string
* @throws {ChecksumError} If input validation fails
*
* @example
* ```typescript
* const checksum = Checksum.generate('hello world');
* // Output: '2a3b' (djb2 hash, 4 chars)
*
* const crc32 = Checksum.generate('data', 'crc32', 8);
* // Output: '8 chars CRC32'
* ```
*/
static generate(input: string, algorithm?: ChecksumAlgorithm, length?: number): string;
/**
* Validates input parameters for checksum generation.
* @private
*/
private static validateInput;
/**
* DJB2 hash algorithm - fast and simple.
* Good for basic integrity checks and short checksums.
*
* @param str - Input string
* @returns 32-bit hash number
*/
private static djb2;
/**
* CRC32 (Cyclic Redundancy Check) - good for error detection.
* Better at detecting errors than simple hashes.
*
* @param str - Input string
* @returns 32-bit CRC32 checksum
*/
private static crc32;
/**
* Adler-32 checksum - fast and good for small data.
* Used in zlib compression.
*
* @param str - Input string
* @returns 32-bit Adler-32 checksum
*/
private static adler32;
/**
* FNV-1a hash - good distribution properties.
* Fast and provides good hash distribution.
*
* @param str - Input string
* @returns 32-bit FNV-1a hash
*/
private static fnv1a;
/**
* MurmurHash3 (simplified version) - high quality hash.
* Good for larger data and cryptographic purposes.
*
* @param str - Input string
* @param seed - Optional seed value for hash initialization
* @returns 32-bit MurmurHash3
*/
private static murmur3;
/**
* Gets or generates CRC32 lookup table (cached for performance).
* @private
*/
private static getCRCTable;
/**
* Vali