All files / customer-management/src/utils uuid-v7.ts

0% Statements 0/17
0% Branches 0/1
0% Functions 0/4
0% Lines 0/17

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45                                                                                         
/**
 * UUID v7 Generator - Using existing implementation from backup-manager
 */
 
export function generateUUIDv7(): string {
  // Get current timestamp in milliseconds
  const timestamp = Date.now();
  
  // Convert timestamp to hex (48 bits)
  const timestampHex = timestamp.toString(16).padStart(12, '0');
  
  // Generate random bits for the rest
  const randomBytes = crypto.getRandomValues(new Uint8Array(10));
  const randomHex = Array.from(randomBytes)
    .map(byte => byte.toString(16).padStart(2, '0'))
    .join('');
  
  // Format as UUID v7: xxxxxxxx-xxxx-7xxx-xxxx-xxxxxxxxxxxx
  const uuid = [
    timestampHex.substring(0, 8),
    timestampHex.substring(8, 12),
    '7' + randomHex.substring(0, 3), // Version 7
    ((parseInt(randomHex.substring(3, 4), 16) & 0x3) | 0x8).toString(16) + randomHex.substring(4, 7), // Variant bits
    randomHex.substring(7, 19)
  ].join('-');
  
  return uuid;
}
 
export function isValidUUIDv7(uuid: string): boolean {
  const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-7[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
  return uuidPattern.test(uuid);
}
 
export function extractTimestampFromUUIDv7(uuid: string): Date | null {
  Iif (!isValidUUIDv7(uuid)) {
    return null;
  }
  
  // Extract first 48 bits (timestamp)
  const timestampHex = uuid.replace(/-/g, '').slice(0, 12);
  const timestamp = parseInt(timestampHex, 16);
  
  return new Date(timestamp);
}