index.browser.js 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
  2. let customAlphabet = (alphabet, defaultSize = 21) => {
  3. // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
  4. // values closer to the alphabet size. The bitmask calculates the closest
  5. // `2^31 - 1` number, which exceeds the alphabet size.
  6. // For example, the bitmask for the alphabet size 30 is 31 (00011111).
  7. // `Math.clz32` is not used, because it is not available in browsers.
  8. let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
  9. // Though, the bitmask solution is not perfect since the bytes exceeding
  10. // the alphabet size are refused. Therefore, to reliably generate the ID,
  11. // the random bytes redundancy has to be satisfied.
  12. // Note: every hardware random generator call is performance expensive,
  13. // because the system call for entropy collection takes a lot of time.
  14. // So, to avoid additional system calls, extra bytes are requested in advance.
  15. // Next, a step determines how many random bytes to generate.
  16. // The number of random bytes gets decided upon the ID size, mask,
  17. // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
  18. // according to benchmarks).
  19. // `-~f => Math.ceil(f)` if f is a float
  20. // `-~i => i + 1` if i is an integer
  21. let step = -~((1.6 * mask * defaultSize) / alphabet.length)
  22. return async (size = defaultSize) => {
  23. let id = ''
  24. while (true) {
  25. let bytes = crypto.getRandomValues(new Uint8Array(step))
  26. // A compact alternative for `for (var i = 0; i < step; i++)`.
  27. let i = step | 0
  28. while (i--) {
  29. // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
  30. id += alphabet[bytes[i] & mask] || ''
  31. if (id.length === size) return id
  32. }
  33. }
  34. }
  35. }
  36. let nanoid = async (size = 21) => {
  37. let id = ''
  38. let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
  39. // A compact alternative for `for (var i = 0; i < step; i++)`.
  40. while (size--) {
  41. // It is incorrect to use bytes exceeding the alphabet size.
  42. // The following mask reduces the random byte in the 0-255 value
  43. // range to the 0-63 value range. Therefore, adding hacks, such
  44. // as empty string fallback or magic numbers, is unneccessary because
  45. // the bitmask trims bytes down to the alphabet size.
  46. let byte = bytes[size] & 63
  47. if (byte < 36) {
  48. // `0-9a-z`
  49. id += byte.toString(36)
  50. } else if (byte < 62) {
  51. // `A-Z`
  52. id += (byte - 26).toString(36).toUpperCase()
  53. } else if (byte < 63) {
  54. id += '_'
  55. } else {
  56. id += '-'
  57. }
  58. }
  59. return id
  60. }
  61. export { nanoid, customAlphabet, random }