UNPKG

@devgrid/common

Version:
53 lines 2.27 kB
import { sha3_512 as sha3 } from '@noble/hashes/sha3'; const defaultLength = 24; const bigLength = 32; const createEntropy = (length = 4, random = Math.random) => { let entropy = ''; while (entropy.length < length) { entropy = entropy + Math.floor(random() * 36).toString(36); } return entropy; }; export function bufToBigInt(buf) { const bits = BigInt(8); let value = BigInt(0); for (const i of buf.values()) { const bi = BigInt(i); value = (value << bits) + bi; } return value; } const hash = (input = '') => bufToBigInt(sha3(input)).toString(36).slice(1); const alphabet = Array.from({ length: 26 }, (x, i) => String.fromCharCode(i + 97)); const randomLetter = (random) => alphabet[Math.floor(random() * alphabet.length)]; export const createFingerprint = ({ globalObj = typeof global !== 'undefined' ? global : typeof window !== 'undefined' ? window : {}, random = Math.random, } = {}) => { const globals = Object.keys(globalObj).toString(); const sourceString = globals.length ? globals + createEntropy(bigLength, random) : createEntropy(bigLength, random); return hash(sourceString).substring(0, bigLength); }; export const createCounter = (count) => () => count++; const initialCountMax = 476782367; export const init = ({ random = Math.random, counter = createCounter(Math.floor(random() * initialCountMax)), length = defaultLength, fingerprint = createFingerprint({ random }), } = {}) => function cuid2() { const firstLetter = randomLetter(random); const time = Date.now().toString(36); const count = counter().toString(36); const salt = createEntropy(length, random); const hashInput = `${time + salt + count + fingerprint}`; return `${firstLetter + hash(hashInput).substring(1, length)}`; }; export const cuid = init({ length: 16, }); export const isCuid = (id, { minLength = 2, maxLength = bigLength } = {}) => { const length = id.length; const regex = /^[a-z][0-9a-z]+$/; try { if (typeof id === 'string' && length >= minLength && length <= maxLength && regex.test(id)) return true; } finally { } return false; }; export const getConstants = () => ({ defaultLength, bigLength }); //# sourceMappingURL=cuid.js.map