UNPKG

ulid-uuid-converter

Version:

A tiny zero dependency library for ULID to UUID conversion and vice versa

79 lines (76 loc) 2.23 kB
// src/base32.ts var B32_CHARACTERS = "0123456789ABCDEFGHJKMNPQRSTVWXYZ"; var crockfordEncode = (input) => { const output = []; let bitsRead = 0; let buffer = 0; const reversedInput = Buffer.from(input).reverse(); for (const byte of reversedInput) { buffer |= byte << bitsRead; bitsRead += 8; while (bitsRead >= 5) { output.unshift(buffer & 31); buffer >>>= 5; bitsRead -= 5; } } if (bitsRead > 0) { output.unshift(buffer & 31); } return output.map((byte) => B32_CHARACTERS.charAt(byte)).join(""); }; var crockfordDecode = (input) => { let sanitizedInput = input.toUpperCase(); sanitizedInput = sanitizedInput.split("").reverse().join(""); const output = []; let bitsRead = 0; let buffer = 0; for (const character of sanitizedInput) { const byte = B32_CHARACTERS.indexOf(character); if (byte === -1) { throw new Error(`Invalid base 32 character found in string: ${character}`); } buffer |= byte << bitsRead; bitsRead += 5; while (bitsRead >= 8) { output.unshift(buffer & 255); buffer >>>= 8; bitsRead -= 8; } } if (bitsRead >= 5 || buffer > 0) { output.unshift(buffer & 255); } return Buffer.from(output); }; // src/regexes.ts var ULID_REGEX = /^[0-7][0-9a-hjkmnp-tv-zA-HJKMNP-TV-Z]{25}$/; var UUID_REGEX = /^[0-9a-fA-F]{8}-(?:[0-9a-fA-F]{4}-){3}[0-9a-fA-F]{12}$/; // src/index.ts function UUIDtoULID(uuid, opts) { const isValid = UUID_REGEX.test(uuid); if (!isValid) { if (opts?.nullOnInvalidInput) { return null; } throw new Error("UUID to ULID conversion failed: invalid UUID input"); } const ulid = crockfordEncode(Buffer.from(uuid.replaceAll("-", ""), "hex")); return ulid; } function ULIDtoUUID(ulid, opts) { const isValid = ULID_REGEX.test(ulid); if (!isValid) { if (opts?.nullOnInvalidInput) { return null; } throw new Error("ULID to UUID conversion failed: invalid ULID input"); } let uuid = crockfordDecode(ulid).toString("hex"); uuid = uuid.substring(0, 8) + "-" + uuid.substring(8, 12) + "-" + uuid.substring(12, 16) + "-" + uuid.substring(16, 20) + "-" + uuid.substring(20); return uuid; } export { ULIDtoUUID, UUIDtoULID };