@devgrid/common
Version:
Some useful primitives
62 lines • 2.68 kB
JavaScript
Object.defineProperty(exports, "__esModule", { value: true });
exports.getConstants = exports.isCuid = exports.cuid = exports.init = exports.createCounter = exports.createFingerprint = void 0;
exports.bufToBigInt = bufToBigInt;
const sha3_1 = require("@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;
};
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((0, sha3_1.sha3_512)(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)];
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);
};
exports.createFingerprint = createFingerprint;
const createCounter = (count) => () => count++;
exports.createCounter = createCounter;
const initialCountMax = 476782367;
const init = ({ random = Math.random, counter = (0, exports.createCounter)(Math.floor(random() * initialCountMax)), length = defaultLength, fingerprint = (0, exports.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)}`;
};
exports.init = init;
exports.cuid = (0, exports.init)({
length: 16,
});
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;
};
exports.isCuid = isCuid;
const getConstants = () => ({ defaultLength, bigLength });
exports.getConstants = getConstants;
//# sourceMappingURL=cuid.js.map
;