电速宝智配引擎
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.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. /* @ts-self-types="./index.d.ts" */
  2. import { urlAlphabet as scopedUrlAlphabet } from './url-alphabet/index.js'
  3. export { urlAlphabet } from './url-alphabet/index.js'
  4. export let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
  5. export let customRandom = (alphabet, defaultSize, getRandom) => {
  6. let safeByteCutoff = 256 - (256 % alphabet.length)
  7. if (safeByteCutoff === 256) {
  8. let mask = alphabet.length - 1
  9. return (size = defaultSize) => {
  10. if (!size) return ''
  11. let id = ''
  12. while (true) {
  13. let bytes = getRandom(size)
  14. let j = size
  15. while (j--) {
  16. id += alphabet[bytes[j] & mask]
  17. if (id.length >= size) return id
  18. }
  19. }
  20. }
  21. }
  22. let step = Math.ceil((1.6 * 256 * defaultSize) / safeByteCutoff)
  23. return (size = defaultSize) => {
  24. if (!size) return ''
  25. let id = ''
  26. while (true) {
  27. let bytes = getRandom(step)
  28. let j = step
  29. while (j--) {
  30. if (bytes[j] < safeByteCutoff) {
  31. id += alphabet[bytes[j] % alphabet.length]
  32. if (id.length >= size) return id
  33. }
  34. }
  35. }
  36. }
  37. }
  38. export let customAlphabet = (alphabet, size = 21) =>
  39. customRandom(alphabet, size | 0, random)
  40. export let nanoid = (size = 21) => {
  41. let id = ''
  42. let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
  43. while (size--) {
  44. id += scopedUrlAlphabet[bytes[size] & 63]
  45. }
  46. return id
  47. }