@shgysk8zer0/suid
Version:
Simple/Sortable Unique IDentifiers
3 lines (2 loc) • 1.39 kB
JavaScript
const t="base64",e="base64url",a=t,r=".",n=12;function o({date:t=Date.now(),randomBits:r=crypto.getRandomValues(new Uint8Array(12)),alphabet:n=a,separator:s="."}={}){if(t instanceof Date)return o({date:t.getTime(),randomBits:r,alphabet:n,separator:s});if(!Number.isSafeInteger(t)||t<1)throw new TypeError("Timestamp must be a Date or positive integer.");if(Number.isSafeInteger(r))return o({date:t,randomBits:crypto.getRandomValues(new Uint8Array(r)),alphabet:n,separator:s});if(!(r instanceof Uint8Array)||r.length<2)throw new TypeError("randomBits must be a non-empty Uint8Array.");if(n===e&&"-"===s)throw new TypeError('"-" is not an allowed separator for base64 URL alphabet.');{const e=Math.floor(r.length/2);return Uint8Array.fromHex(t.toString(16).padStart(12,"0")).toBase64({alphabet:n})+s+r.subarray(0,e).toBase64({alphabet:n})+s+r.subarray(e).toBase64({alphabet:n})}}function s(t,{alphabet:e=a,separator:r="."}={}){if("string"!=typeof t||0===t.length)throw new TypeError("suid must be a non-empty string.");{const[a,n,o]=t.split(r).map((t=>Uint8Array.fromBase64(t,{alphabet:e}))),s=new Uint8Array(n.length+o.length);s.set(n,0),s.set(o,n.length);return{date:new Date(parseInt(a.toHex(),16)),randomBits:s,alphabet:e,separator:r}}}export{a as ALPHABET,t as BASE64,e as BASE64_URL,n as RANDOM_BITS,r as SEPARATOR,o as getSUID,s as parseSUID};
//# sourceMappingURL=suid.min.js.map