@applitools/utils
Version:
49 lines (48 loc) • 1.92 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.uuid = void 0;
const isNode = () => typeof process !== 'undefined' && process.versions != null && process.versions.node != null;
const isWebCryptoAvailable = () => typeof window !== 'undefined' && window.crypto != null && typeof window.crypto.randomUUID === 'function';
const generateNodeUUID = () => {
// We use a dynamic require('crypto') here to ensure this code doesn't break
// when bundled for a browser environment, which does not have a 'crypto' module.
// A static, top-level `import crypto from 'crypto'` would cause bundler errors.
const cryptoModule = 'crypto';
const crypto = require(cryptoModule);
// Use the modern, fast method if available (Node.js >= 14.17.0)
if (typeof crypto.randomUUID === 'function') {
return crypto.randomUUID();
}
// Fallback for older Node.js versions using the still-secure randomBytes.
const bytes = crypto.randomBytes(16);
// Set the version to 4 as per RFC 4122
bytes[6] = (bytes[6] & 0x0f) | 0x40;
// Set the variant to RFC 4122
bytes[8] = (bytes[8] & 0x3f) | 0x80;
const hex = bytes.toString('hex');
return [
hex.substring(0, 8),
hex.substring(8, 12),
hex.substring(12, 16),
hex.substring(16, 20),
hex.substring(20),
].join('-');
};
const generateFallbackUUID = () => {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, c => {
const r = (Math.random() * 16) | 0;
const v = c === 'x' ? r : (r & 0x3) | 0x8;
return v.toString(16);
});
};
/**
* Generates a UUID v4 string (cryptographically secure if possible).
*/
const uuid = () => {
if (isNode())
return generateNodeUUID();
if (isWebCryptoAvailable())
return window.crypto.randomUUID();
return generateFallbackUUID();
};
exports.uuid = uuid;
;