hybrid-id-generator
Version:
A powerful hybrid ID generator that combines timestamps, machine IDs, random bits, and sequence numbers to create globally unique identifiers. Features collision prevention, Base62 encoding, and optional ID expiry tracking, ideal for distributed systems a
64 lines (63 loc) • 2.38 kB
TypeScript
export type MachineIDStrategy = 'env' | 'network' | 'random' | undefined;
/**
* Interface for machine ID providers.
* Allows different strategies for generating or retrieving the machine ID.
*/
export interface MachineIDProvider {
getMachineId(): number;
}
/**
* Environment-based machine ID provider.
* Retrieves the machine ID from a specified environment variable and caches it.
*/
export declare class EnvMachineIDProvider implements MachineIDProvider {
private envVarName;
private cachedMachineId;
constructor(envVarName?: string);
getMachineId(): number;
}
/**
* Network-based machine ID provider.
* Generates a machine ID based on the MAC address of the network interface and caches it.
* This provider can handle multiple MAC addresses and offers configuration options.
*/
export declare class NetworkMachineIDProvider implements MachineIDProvider {
private interfaceName?;
private cachedMachineId;
/**
* @param interfaceName Optional name of the network interface to use.
* If not provided, the first valid MAC address found will be used.
*/
constructor(interfaceName?: string);
getMachineId(): number;
private getValidMac;
private hashMacToMachineId;
}
/**
* Random machine ID provider.
* Generates a random machine ID within a specified range.
* This implementation uses cryptographic random values to improve security and reduce predictability.
*/
export declare class RandomMachineIDProvider implements MachineIDProvider {
private maxMachineId;
/**
* @param maxMachineId Maximum value for the machine ID. Defaults to 1023.
*/
constructor(maxMachineId?: number);
getMachineId(): number;
private generateRandomMachineId;
private getCryptographicRandomValue;
}
/**
* Factory for creating MachineIDProvider based on strategy.
*/
export declare class MachineIDProviderFactory {
/**
* Create a MachineIDProvider based on the strategy and a single var that is interpreted based on the strategy.
* - If the strategy is 'env', the var is treated as envVarName.
* - If the strategy is 'random', the var is treated as maxMachineId.
* - 'network' strategy doesn't require an additional var.
*/
static createMachineIDProvider(strategy: MachineIDStrategy, value?: string | number): MachineIDProvider;
}
export default MachineIDProvider;