index.d.ts 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. import {MergeExclusive} from 'type-fest';
  2. interface BaseOptions {
  3. /**
  4. Length of the returned string.
  5. */
  6. length: number;
  7. }
  8. interface TypeOption {
  9. /**
  10. Use only characters from a predefined set of allowed characters.
  11. Cannot be set at the same time as the `characters` option.
  12. @default 'hex'
  13. The `distinguishable` set contains only uppercase characters that are not easily confused: `CDEHKMPRTUWXY012458`. It can be useful if you need to print out a short string that you'd like users to read and type back in with minimal errors. For example, reading a code off of a screen that needs to be typed into a phone to connect two devices.
  14. @example
  15. ```
  16. cryptoRandomString({length: 10});
  17. //=> '87fc70e2b9'
  18. cryptoRandomString({length: 10, type: 'base64'});
  19. //=> 'mhsX7xmIv/'
  20. cryptoRandomString({length: 10, type: 'url-safe'});
  21. //=> 'VEjfNW3Yej'
  22. cryptoRandomString({length: 10, type: 'numeric'});
  23. //=> '8314659141'
  24. cryptoRandomString({length: 6, type: 'distinguishable'});
  25. //=> 'CDEHKM'
  26. ```
  27. */
  28. type?: 'hex' | 'base64' | 'url-safe' | 'numeric' | 'distinguishable';
  29. }
  30. interface CharactersOption {
  31. /**
  32. Use only characters from a custom set of allowed characters.
  33. Cannot be set at the same time as the `type` option.
  34. Minimum length: `1`
  35. Maximum length: `65536`
  36. @example
  37. ```
  38. cryptoRandomString({length: 10, characters: '0123456789'});
  39. //=> '8796225811'
  40. ```
  41. */
  42. characters?: string;
  43. }
  44. declare namespace cryptoRandomString {
  45. type Options = BaseOptions & MergeExclusive<TypeOption, CharactersOption>;
  46. }
  47. /**
  48. Generate a [cryptographically strong](https://en.wikipedia.org/wiki/Strong_cryptography) random string.
  49. @returns A randomized string.
  50. @example
  51. ```
  52. import cryptoRandomString = require('crypto-random-string');
  53. cryptoRandomString({length: 10});
  54. //=> '2cf05d94db'
  55. ```
  56. */
  57. declare function cryptoRandomString(options?: cryptoRandomString.Options): string;
  58. export = cryptoRandomString;