Peter Marshall | 4e161df | 2020-11-10 12:29:38 | [diff] [blame] | 1 | /** |
| 2 | * Generate secure URL-friendly unique ID. The non-blocking version. |
| 3 | * |
| 4 | * By default, the ID will have 21 symbols to have a collision probability |
| 5 | * similar to UUID v4. |
| 6 | * |
| 7 | * ```js |
| 8 | * import { nanoid } from 'nanoid/async' |
| 9 | * nanoid().then(id => { |
| 10 | * model.id = id |
| 11 | * }) |
| 12 | * ``` |
| 13 | * |
| 14 | * @param size Size of the ID. The default size is 21. |
| 15 | * @returns A promise with a random string. |
| 16 | */ |
Tim van der Lippe | 324d603 | 2021-06-21 15:43:26 | [diff] [blame^] | 17 | export function nanoid(size?: number): Promise<string> |
Peter Marshall | 4e161df | 2020-11-10 12:29:38 | [diff] [blame] | 18 | |
| 19 | /** |
| 20 | * A low-level function. |
| 21 | * Generate secure unique ID with custom alphabet. The non-blocking version. |
| 22 | * |
| 23 | * Alphabet must contain 256 symbols or less. Otherwise, the generator |
| 24 | * will not be secure. |
| 25 | * |
| 26 | * @param alphabet Alphabet used to generate the ID. |
| 27 | * @param size Size of the ID. |
| 28 | * @returns A promise with a random string. |
| 29 | * |
| 30 | * ```js |
| 31 | * import { customAlphabet } from 'nanoid/async' |
| 32 | * const nanoid = customAlphabet('0123456789абвгдеё', 5) |
| 33 | * nanoid().then(id => { |
| 34 | * model.id = id //=> "8ё56а" |
| 35 | * }) |
| 36 | * ``` |
| 37 | */ |
Tim van der Lippe | 324d603 | 2021-06-21 15:43:26 | [diff] [blame^] | 38 | export function customAlphabet( |
Peter Marshall | 4e161df | 2020-11-10 12:29:38 | [diff] [blame] | 39 | alphabet: string, |
| 40 | size: number |
| 41 | ): () => Promise<string> |
| 42 | |
| 43 | /** |
| 44 | * Generate an array of random bytes collected from hardware noise. |
| 45 | * |
| 46 | * ```js |
| 47 | * import { random } from 'nanoid/async' |
| 48 | * random(5).then(bytes => { |
| 49 | * bytes //=> [10, 67, 212, 67, 89] |
| 50 | * }) |
| 51 | * ``` |
| 52 | * |
| 53 | * @param bytes Size of the array. |
| 54 | * @returns A promise with a random bytes array. |
| 55 | */ |
Tim van der Lippe | 324d603 | 2021-06-21 15:43:26 | [diff] [blame^] | 56 | export function random(bytes: number): Promise<Uint8Array> |