UNPKG

idgenie

Version:

A magical and flexible ID generator with support for unique IDs, date/time, prefixes, suffixes, and more.

132 lines (131 loc) 5.18 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); Object.defineProperty(exports, "__esModule", { value: true }); exports.uniqueId = uniqueId; const crypto = __importStar(require("crypto")); // Default alphabet: alphanumeric const DEFAULT_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'; // Internal counter for counter-based uniqueness let internalCounter = 0; /** * Generates a flexible unique ID based on options. * @param options - Configuration options for ID generation. * @returns A generated unique string ID. * @throws {TypeError} If length is invalid. */ function uniqueId(options = {}) { const { length = 8, randomLength = false, prefix = '', suffix = '', includeDate = false, includeTime = false, dateLocale = 'en-IN', timeLocale = 'en-IN', dateFormatOptions, timeFormatOptions, alphabet = DEFAULT_ALPHABET, casing = "mixed", separator = "", secure = false, mode = "random", counter = false, timestamp = false, } = options; // Handle UUID separately if (mode === "uuid") { return generateUUID(); } // Validate length strictly if (typeof length !== 'number' || length <= 0 || !Number.isFinite(length)) { throw new TypeError(`"length" must be a positive number. Received: ${length}`); } // Random length support const actualLength = !randomLength ? length : Math.floor(Math.random() * (36 - 8 + 1)) + 8; // between 8-36 chars // Generate randomness (secure vs Math.random) const randomPart = secure ? generateSecureRandom(alphabet, actualLength) : generateMathRandom(alphabet, actualLength); // Apply casing let finalRandomPart = randomPart; if (casing === "lower") finalRandomPart = randomPart.toLowerCase(); else if (casing === "upper") finalRandomPart = randomPart.toUpperCase(); // Generate date/time/timestamp strings let dateTimeStr = ""; if (timestamp) { dateTimeStr = Date.now().toString(); } else { const now = new Date(); if (includeDate) { let dateStr = ""; dateStr = now.toLocaleDateString(dateLocale, dateFormatOptions || { year: "numeric", month: "2-digit", day: "2-digit" }).replace(/[^a-zA-Z0-9]/g, separator); dateTimeStr += dateStr; } if (includeTime) { let timeStr = ""; timeStr = now.toLocaleTimeString(timeLocale, timeFormatOptions || { hour: "2-digit", minute: "2-digit", second: "2-digit" }).replace(/[^a-zA-Z0-9]/g, separator); dateTimeStr += separator + timeStr; } } // Counter support let counterStr = ""; if (counter) { counterStr = (internalCounter++).toString(); } // Final ID assembly return `${prefix}${finalRandomPart}${dateTimeStr ? dateTimeStr + separator : ''}${counterStr}${suffix}`; } /** * Generates random string using crypto.randomBytes. */ function generateSecureRandom(alphabet, length) { const bytes = crypto.randomBytes(length); let result = ''; for (let i = 0; i < length; i++) { result += alphabet[bytes[i] % alphabet.length]; } return result; } /** * Generates random string using Math.random(). */ function generateMathRandom(alphabet, length) { let result = ''; for (let i = 0; i < length; i++) { result += alphabet.charAt(Math.floor(Math.random() * alphabet.length)); } return result; } /** * Generates UUID v4. */ function generateUUID() { if (typeof crypto !== 'undefined' && crypto.randomUUID) { return crypto.randomUUID(); } // Fallback: use a polyfill or custom implementation return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); return v.toString(16); }); }