index.cjs 3.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. let crypto = require('crypto')
  2. let { urlAlphabet } = require('./url-alphabet/index.cjs')
  3. // It is best to make fewer, larger requests to the crypto module to
  4. // avoid system call overhead. So, random numbers are generated in a
  5. // pool. The pool is a Buffer that is larger than the initial random
  6. // request size by this multiplier. The pool is enlarged if subsequent
  7. // requests exceed the maximum buffer size.
  8. const POOL_SIZE_MULTIPLIER = 128
  9. let pool, poolOffset
  10. let fillPool = bytes => {
  11. if (bytes < 0 || bytes > 1024) throw new RangeError('Wrong ID size')
  12. if (!pool || pool.length < bytes) {
  13. pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
  14. crypto.randomFillSync(pool)
  15. poolOffset = 0
  16. } else if (poolOffset + bytes > pool.length) {
  17. crypto.randomFillSync(pool)
  18. poolOffset = 0
  19. }
  20. poolOffset += bytes
  21. }
  22. let random = bytes => {
  23. // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
  24. fillPool((bytes |= 0))
  25. return pool.subarray(poolOffset - bytes, poolOffset)
  26. }
  27. let customRandom = (alphabet, defaultSize, getRandom) => {
  28. // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
  29. // values closer to the alphabet size. The bitmask calculates the closest
  30. // `2^31 - 1` number, which exceeds the alphabet size.
  31. // For example, the bitmask for the alphabet size 30 is 31 (00011111).
  32. let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
  33. // Though, the bitmask solution is not perfect since the bytes exceeding
  34. // the alphabet size are refused. Therefore, to reliably generate the ID,
  35. // the random bytes redundancy has to be satisfied.
  36. // Note: every hardware random generator call is performance expensive,
  37. // because the system call for entropy collection takes a lot of time.
  38. // So, to avoid additional system calls, extra bytes are requested in advance.
  39. // Next, a step determines how many random bytes to generate.
  40. // The number of random bytes gets decided upon the ID size, mask,
  41. // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
  42. // according to benchmarks).
  43. let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
  44. return (size = defaultSize) => {
  45. let id = ''
  46. while (true) {
  47. let bytes = getRandom(step)
  48. // A compact alternative for `for (let i = 0; i < step; i++)`.
  49. let i = step
  50. while (i--) {
  51. // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
  52. id += alphabet[bytes[i] & mask] || ''
  53. if (id.length === size) return id
  54. }
  55. }
  56. }
  57. }
  58. let customAlphabet = (alphabet, size = 21) =>
  59. customRandom(alphabet, size, random)
  60. let nanoid = (size = 21) => {
  61. // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
  62. fillPool((size |= 0))
  63. let id = ''
  64. // We are reading directly from the random pool to avoid creating new array
  65. for (let i = poolOffset - size; i < poolOffset; i++) {
  66. // It is incorrect to use bytes exceeding the alphabet size.
  67. // The following mask reduces the random byte in the 0-255 value
  68. // range to the 0-63 value range. Therefore, adding hacks, such
  69. // as empty string fallback or magic numbers, is unneccessary because
  70. // the bitmask trims bytes down to the alphabet size.
  71. id += urlAlphabet[pool[i] & 63]
  72. }
  73. return id
  74. }
  75. module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }