@catbee/utils
Version:
A modular, production-grade utility toolkit for Node.js and TypeScript, designed for robust, scalable applications (including Express-based services). All utilities are tree-shakable and can be imported independently.
61 lines • 1.95 kB
JavaScript
import { randomUUID, randomBytes } from "crypto";
/**
* Generates a UUID v4 string (RFC 4122).
*
* @returns {string} UUID v4 (e.g., 'c0de1234-5678-9abc-def0-123456789abc')
*/
export function uuid() {
return randomUUID();
}
/**
* Generates a nanoid-style random ID (URL-safe, customizable length).
*
* @param {number} length - Length of the ID (default: 21).
* @returns {string} Nanoid-style random string.
*/
export function nanoId(length = 21) {
if (length <= 0)
return "";
let id = "";
while (id.length < length) {
id += randomBytes(Math.ceil((length * 3) / 4))
.toString("base64url")
.replace(/[+/=]/g, "");
}
return id.slice(0, length);
}
/**
* Generates a cryptographically strong random hex string.
*
* @param {number} byteLength - Number of random bytes (default: 16 → 32 hex chars).
* @returns {string} Random hex string.
*/
export function randomHex(byteLength = 16) {
// Use Node.js crypto for both Node and browser compatibility
// Prefer randomBytes if available (Node), fallback to getRandomValues for browser (not used here)
return randomBytes(byteLength)
.toString("hex")
.padStart(byteLength * 2, "0")
.slice(0, byteLength * 2);
}
/**
* Generates a random integer between min (inclusive) and max (inclusive).
*
* @param {number} min - Minimum value.
* @param {number} max - Maximum value.
* @returns {number} Random integer in range.
*/
export function randomInt(min, max) {
const range = max - min + 1;
return Math.floor(Math.random() * range) + min;
}
/**
* Generates a cryptographically strong random base64 string.
*
* @param {number} byteLength - Number of random bytes (default: 16).
* @returns {string} Random base64 string (URL-safe, no padding).
*/
export function randomBase64(byteLength = 16) {
return randomBytes(byteLength).toString("base64url");
}
//# sourceMappingURL=id.utils.js.map