电速宝智配引擎
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. import { webcrypto as crypto } from 'node:crypto'
  2. import { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'
  3. export { urlAlphabet } from './url-alphabet/index.js'
  4. const POOL_SIZE_MULTIPLIER = 128
  5. let pool, poolOffset
  6. function fillPool(bytes) {
  7. if (!pool || pool.length < bytes) {
  8. pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
  9. crypto.getRandomValues(pool)
  10. poolOffset = 0
  11. } else if (poolOffset + bytes > pool.length) {
  12. crypto.getRandomValues(pool)
  13. poolOffset = 0
  14. }
  15. poolOffset += bytes
  16. }
  17. export function random(bytes) {
  18. fillPool((bytes |= 0))
  19. return pool.subarray(poolOffset - bytes, poolOffset)
  20. }
  21. export function customRandom(alphabet, defaultSize, getRandom) {
  22. let safeByteCutoff = 256 - (256 % alphabet.length)
  23. if (safeByteCutoff === 256) {
  24. let mask = alphabet.length - 1
  25. return (size = defaultSize) => {
  26. if (!size) return ''
  27. let id = ''
  28. while (true) {
  29. let bytes = getRandom(size)
  30. let i = size
  31. while (i--) {
  32. id += alphabet[bytes[i] & mask]
  33. if (id.length >= size) return id
  34. }
  35. }
  36. }
  37. }
  38. let step = Math.ceil((1.6 * 256 * defaultSize) / safeByteCutoff)
  39. return (size = defaultSize) => {
  40. if (!size) return ''
  41. let id = ''
  42. while (true) {
  43. let bytes = getRandom(step)
  44. let i = step
  45. while (i--) {
  46. if (bytes[i] < safeByteCutoff) {
  47. id += alphabet[bytes[i] % alphabet.length]
  48. if (id.length >= size) return id
  49. }
  50. }
  51. }
  52. }
  53. }
  54. export function customAlphabet(alphabet, size = 21) {
  55. return customRandom(alphabet, size, random)
  56. }
  57. export function nanoid(size = 21) {
  58. fillPool((size |= 0))
  59. let id = ''
  60. for (let i = poolOffset - size; i < poolOffset; i++) {
  61. id += scopedUrlAlphabet[pool[i] & 63]
  62. }
  63. return id
  64. }