index.browser.js 2.6 KB

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