uuid.ts 734 B

1234567891011121314151617
  1. /**
  2. * Utility function to generate a UUID.
  3. * A wrapper for crypto.randomUUID() that provides a fallback for non-secure contexts (HTTP, older browsers, etc.).
  4. */
  5. export const generateUUID = (): string => {
  6. // Check if crypto.randomUUID is available (only available in secure contexts like HTTPS/localhost)
  7. if (typeof crypto !== 'undefined' && typeof crypto.randomUUID === 'function') {
  8. return crypto.randomUUID();
  9. }
  10. // Fallback for non-secure contexts or older browsers (RFC4122 v4 compatible)
  11. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, (c) => {
  12. const r = (Math.random() * 16) | 0;
  13. const v = c === 'x' ? r : (r & 0x3) | 0x8;
  14. return v.toString(16);
  15. });
  16. };