nehoid
Version:
Advanced unique ID generation utility with multi-layer encoding, collision detection, and context-aware features
645 lines (632 loc) • 20.5 kB
TypeScript
type ENC_TYPE = "percentEncoding" | "doublepercent" | "base64" | "hex" | "unicode" | "htmlEntity" | "punycode" | "asciihex" | "asciioct" | "rot13" | "base32" | "urlSafeBase64" | "jsEscape" | "cssEscape" | "utf7" | "quotedPrintable" | "decimalHtmlEntity" | "rawHexadecimal" | "jwt" | "url" | "rawHex";
declare class Encoder {
static encode(input: string, encodings: ENC_TYPE | ENC_TYPE[]): Promise<string>;
static decode(input: string, encodings: ENC_TYPE | ENC_TYPE[], opt?: {
autoDetect?: boolean;
}): string;
static compress(input: string, method: "lz77" | "gzip"): string;
static decompress(input: string, method: "lz77" | "gzip"): string;
}
/**
* EncodingPipeline class for NehoID
* Provides a fluent interface for building encoding pipelines
*/
declare class EncodingPipeline {
private encoders;
private compressionMethod;
private isReversible;
private metadata;
/**
* Add an encoder to the pipeline
* @param encoder Encoding type to add
* @returns The pipeline instance for chaining
*/
addEncoder(encoder: ENC_TYPE): EncodingPipeline;
/**
* Add multiple encoders to the pipeline
* @param encoders Array of encoding types to add
* @returns The pipeline instance for chaining
*/
addEncoders(encoders: ENC_TYPE[]): EncodingPipeline;
/**
* Add compression to the pipeline
* @param method Compression method to use
* @returns The pipeline instance for chaining
*/
addCompression(method: "lz77" | "gzip"): EncodingPipeline;
/**
* Enable reversibility for the pipeline
* @returns The pipeline instance for chaining
*/
enableReversibility(): EncodingPipeline;
/**
* Disable reversibility for the pipeline
* @returns The pipeline instance for chaining
*/
disableReversibility(): EncodingPipeline;
/**
* Add metadata to the pipeline
* @param key Metadata key
* @param value Metadata value
* @returns The pipeline instance for chaining
*/
addMetadata(key: string, value: any): EncodingPipeline;
/**
* Process input through the pipeline
* @param input String to process
* @returns Processed string
*/
process(input: string): string;
/**
* Reverse the pipeline processing (if reversible)
* @param input Processed string to reverse
* @returns Original string or null if not reversible
*/
reverse(input: string): string | null;
/**
* Get the pipeline configuration
* @returns Configuration object
*/
getConfig(): {
encoders: ENC_TYPE[];
compression: "none" | "lz77" | "gzip";
reversible: boolean;
metadata: Record<string, any>;
};
}
/**
* Express middleware options
*/
interface MiddlewareOptions {
/** Header name to use for the request ID */
header?: string;
/** ID format to use */
format?: "standard" | "uuid" | "short" | "nano";
/** Whether to expose the ID as a response header */
exposeHeader?: boolean;
/** Whether to add the ID to the request object */
addToRequest?: boolean;
/** Custom ID generator function */
generator?: () => string;
/**
* Generate a name while requesting.
* @default NehoID
*
* @example ```js
* const headerId = req.NehoID
*
* console.log(headerId) //undefined or something-like-this
* ```
*
*/
name4Req?: string;
}
/**
* Create Express middleware for request ID generation
* @param options Middleware configuration options
* @returns Express middleware function
*/
declare function createMiddleware(options?: MiddlewareOptions): (req: any, res: any, next: Function) => void;
/**
* 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;
interface IdGeneratorOptions {
size?: number;
segments?: number;
separator?: string;
encoding?: ENC_TYPE | ENC_TYPE[];
prefix?: string;
includeTimestamp?: boolean;
alphabet?: string;
compression?: 'none' | 'lz77' | 'gzip';
reversible?: boolean;
}
interface CollisionStrategy {
name: string;
maxAttempts: number;
backoffType: 'linear' | 'exponential';
checkFunction: (id: string) => Promise<boolean>;
}
interface ContextOptions {
includeDevice?: boolean;
includeTimezone?: boolean;
includeBrowser?: boolean;
includeScreen?: boolean;
includeLocation?: boolean;
userBehavior?: string;
}
interface SemanticOptions {
prefix?: string;
region?: string;
department?: string;
year?: number;
customSegments?: Record<string, string | number>;
}
interface BatchOptions {
count: number;
format?: 'standard' | 'nano' | 'short' | 'uuid';
parallel?: boolean;
ensureUnique?: boolean;
}
interface ValidationOptions {
checkFormat?: boolean;
checkCollisions?: boolean;
repairCorrupted?: boolean;
}
interface HealthScore {
score: number;
entropy: 'low' | 'medium' | 'high';
predictability: 'low' | 'medium' | 'high';
recommendations: string[];
}
interface Stats {
generated: number;
collisions: number;
averageGenerationTime: string;
memoryUsage: string;
distributionScore: number;
}
interface MigrationOptions {
from: string;
to: string;
preserveOrder?: boolean;
batchSize?: number;
ids?: string[];
count?: number;
}
interface CompatibilityOptions {
platform: ('javascript' | 'python' | 'go')[];
format: string;
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;
}
/**
* @author NEHONIX
* @since 20/05/2025
* @see lab.nehonix.space
* NehoId is an advanced unique ID generation utility with multi-layer encoding, collision detection, and context-aware features
* -------------------------------------------------------------------------------------------
* @example
* ```js
* const id = NehoID.generate({ prefix: "usr" });
console.log(id); // "6a617977416b714d-7938716a56515a52-79764d5a50775555"
const customStrategy: CollisionStrategy = {
name: "database-check",
maxAttempts: 3,
backoffType: "exponential",
checkFunction: async (id) => {
return !(await myDatabase.findById(id));
},
};
* ```
*
*/
declare class NehoID extends NehoIDV2 {
private static monitoringEnabled;
private static stats;
static middleware(...p: Parameters<typeof createMiddleware>): (req: any, res: any, next: Function) => void;
static generate(options?: Partial<IdGeneratorOptions>): string;
static safe(options: CollisionStrategy): Promise<string>;
static uuid(): string;
static nanoid(length?: number): string;
static short(length?: number): string;
static hex(length?: number): string;
/**
* Generates a hierarchical ID with parent-child relationships
* @param options Hierarchical ID options
* @returns A hierarchical ID
*/
static hierarchical(options?: {}): string;
/**
* Generates a time-ordered ID for chronological sorting
* @param options Temporal ID options
* @returns A temporal ID with timestamp
*/
static temporal(options?: {}): string;
/**
* Generates a sequential ID suitable for database use
* @param options Sequential ID options
* @returns A sequential ID
*/
static sequential(options: {
prefix?: string;
counter: number;
padLength?: number;
suffix?: boolean;
}): string;
static batch(options: BatchOptions): string[];
static validate(id: string, options?: ValidationOptions): boolean;
static validateBatch(ids: string[], options?: ValidationOptions): {
valid: string[];
invalid: string[];
duplicates: string[];
};
static healthCheck(id: string): HealthScore;
static startMonitoring(): void;
static stopMonitoring(): void;
static getStats(): Stats;
/**
* Hashes geographic coordinates for privacy
* @param latitude Latitude coordinate
* @param longitude Longitude coordinate
* @returns A hashed string representation of the coordinates
*/
private static hashCoordinates;
private static updateStats;
/**
* Generates a context-aware ID that incorporates environmental information
* @param options Context options for ID generation
* @returns A context-aware unique ID
*/
static contextual(options: ContextOptions): string;
/**
* Generates a semantic ID that incorporates meaningful information
* @param options Semantic options for ID generation
* @returns A semantic unique ID
*/
static semantic(options: SemanticOptions): string;
/**
* Migrates IDs from one format to another
* @param options Migration options
* @returns Promise resolving to an array of migrated IDs
*/
static migrate(options: MigrationOptions): Promise<string[]>;
/**
* Generates an ID that is compatible with specified platforms
* @param options Compatibility options
* @returns A compatible ID
*/
static compatible(options: CompatibilityOptions): string;
}
declare const NehoIDMiddleware: typeof createMiddleware;
declare const database: {
mongoose: typeof mongooseField;
sequelize: typeof sequelizeField;
typeorm: typeof typeormDecorator;
};
export { Encoder, EncodingPipeline, NehoID, NehoIDMiddleware, database };
export type { BatchOptions, CollisionStrategy, CompatibilityOptions, ContextOptions, HealthScore, IdGeneratorOptions, MigrationOptions, SemanticOptions, Stats, ValidationOptions };