Skip to content
Myr

Change API for custom alphabet and random

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Andrey Sitnik · committed by Andrey Sitnik · parent b488b48 · Browse files · 15 files+174 added−157 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

15 files+174 added−157 removed

  • tests:+38 added−30 removed
  • other:+136 added−127 removed

15 files+174 added−157 removed

modified:async/index.browser.js+18 added-16 removed
modified:async/index.d.ts+7 added-3 removed
modified:async/index.js+6 added-6 removed
modified:non-secure/index.d.ts+4 added-3 removed
19 unmodified lines
20 * @param alphabet Symbols to be used in ID.21 * @returns Random string.22 *23 * ```js24 * const { nanoid2 } = require('nanoid/non-secure')25 * model.id = generate(5, '0123456789абвгдеё') //=> "8ё56а"24 * import { customAlphabet } from 'nanoid/non-secure'25 * const nanoid = customAlphabet('0123456789абвгдеё', 5)26 * model.id = //=> "8ё56а"27 * ```28 */28export function nanoid2 (size: number, alphabet: string): string29export function customAlphabet (alphabet: string, size: number): () => string
modified:non-secure/index.js+17 added-22 removed
1let nanoid2 = (size, alphabet) => {2 let id = ''3 // Complete alternative for `for (var i = 0; i < size; i++)`4 while (size--) {5 // `| 0` is compact and faster alternative for `Math.floor()`6 id += alphabet[Math.random() * alphabet.length | 0]1let { urlAlphabet } = require('..')23let customAlphabet = (alphabet, size) => {4 return () => {5 let id = ''6 // Complete alternative for `for (var i = 0; i < size; i++)`7 let i = size8 while (i--) {9 // `| 0` is compact and faster alternative for `Math.floor()`10 id += alphabet[Math.random() * alphabet.length | 0]11 }12 return id13 }8 return id14}1516let nanoid = (size = 21) => {17 let id = ''13 // Compact alternative for `for (var i = 0; i < size; i++)`14 while (size--) {18 // Complete alternative for `for (var i = 0; i < size; i++)`19 let i = size20 while (i--) {21 // `| 0` is compact and faster alternative for `Math.floor()`16 let byte = Math.random() * 64 | 017 if (byte < 36) {18 // 0-9a-z19 id += byte.toString(36)20 } else if (byte < 62) {21 // A-Z22 id += (byte - 26).toString(36).toUpperCase()23 } else if (byte < 63) {24 id += '_'25 } else {26 id += '-'27 }22 id += urlAlphabet[Math.random() * 64 | 0]23 }24 return id25}2632module.exports = { nanoid, nanoid2 }27module.exports = { nanoid, customAlphabet }
modified:test/demo/index.js+4 added-2 removed
1 unmodified line
2import { v4 as uuid4 } from 'uuid'3import rndm from 'rndm'4import uid from 'uid-safe'56import { nanoid, nanoid2, random } from '../../'6import { nanoid, customAlphabet, random } from '../../'7import { nanoid as nonSecure } from '../../non-secure'89const COUNT = 50 * 100010const ALPHABET = 'abcdefghijklmnopqrstuvwxyz'11const LENGTH = ALPHABET.length1213let nanoid2 = customAlphabet(ALPHABET, LENGTH)1415function print (number) {16 return String(Math.floor(number * 100))17 .replace(/\d{6}$/, ',$&')18 .replace(/\d{3}$/, ',$&')
52 unmodified lines
71 }72 return result73 }),74 () => printDistr('nanoid', () => nanoid()),73 () => printDistr('nanoid2', () => nanoid2(ALPHABET, LENGTH)),75 () => printDistr('nanoid2', () => nanoid2()),76 () => printDistr('uid.sync', () => uid.sync(21)),77 () => printDistr('uuid/v4', () => uuid4()),78 () => printDistr('shortid', () => shortid()),79 () => printDistr('rndm', () => rndm()),
20 unmodified lines
modified:test/async.test.js+6 added-4 removed
24 unmodified lines
25}2627for (let type of ['node', 'browser']) {28 describe(`${ type }`, () => {29 let { nanoid, nanoid2 } = type === 'node' ? node : browser29 let { nanoid, customAlphabet } = type === 'node' ? node : browser3031 describe('nanoid', () => {32 function mock (callback) {33 crypto.randomFill = callback
71 unmodified lines
105 })106 }107 })108109 describe('nanoid2', () => {109 describe('customAlphabet', () => {110 it('has options', async () => {111 let nanoidA = customAlphabet('a', 5)111 let id = await nanoid2(5, 'a')112 let id = await nanoidA()113 expect(id).toEqual('aaaaa')114 })115116 it('has flat distribution', async () => {117 let COUNT = 100 * 1000118 let LENGTH = 5119 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'120 let nanoid2 = customAlphabet(ALPHABET, LENGTH)121122 let chars = { }123 await Promise.all(times(100, async () => {122 let id = await nanoid2(LENGTH, ALPHABET)124 let id = await nanoid2()125 expect(id).toHaveLength(LENGTH)126 for (let char of id) {127 if (!chars[char]) chars[char] = 0128 chars[char] += 1
15 unmodified lines
modified:test/benchmark+10 added-7 removed
6 unmodified lines
7let rndm = require('rndm')8let srs = require('secure-random-string')9let uid = require('uid-safe')1011let { nanoid: asyncNanoid, nanoid2: asyncNanoid2 } = require('../async')11let { nanoid: aNanoid, customAlphabet: aCustomAlphabet } = require('../async')12let { nanoid, customAlphabet } = require('../')13let { nanoid: nonSecure } = require('../non-secure')13let { nanoid, nanoid2 } = require('../')1415let suite = new benchmark.Suite()1617let nanoid2 = customAlphabet('1234567890abcdef-', 10)18let asyncNanoid2 = aCustomAlphabet('1234567890abcdef-', 10)1920function formatNumber (number) {21 return String(number)22 .replace(/\d{3}$/, ',$&')23 .replace(/^(\d)(\d{3})/, '$1,$2')
2 unmodified lines
26suite27 .add('nanoid', () => {28 nanoid()29 })27 .add('nanoid2', () => {28 nanoid2(10, '1234567890abcdef-')30 .add('customAlphabet', () => {31 nanoid2()32 })33 .add('uid.sync', () => {34 uid.sync(14)35 })
8 unmodified lines
44 })45 .add('async nanoid', {46 defer: true,47 fn (defer) {45 asyncNanoid().then(() => {48 aNanoid().then(() => {49 defer.resolve()50 })51 }52 })50 .add('async nanoid2', {53 .add('async customAlphabet', {54 defer: true,55 fn (defer) {53 asyncNanoid2(10, '1234567890abcdef-').then(() => {56 asyncNanoid2().then(() => {57 defer.resolve()58 })59 }60 })
33 unmodified lines
modified:test/index.test.js+12 added-13 removed
12 unmodified lines
13let node = require('../index.js')1415for (let type of ['node', 'browser']) {16 describe(`${ type }`, () => {17 let { nanoid, nanoid2, nanoid3, random, urlAlphabet } =17 let { nanoid, customAlphabet, customRandom, random, urlAlphabet } =18 type === 'node' ? node : browser1920 describe('nanoid', () => {21 it('generates URL-friendly IDs', () => {
49 unmodified lines
71 expect(max - min).toBeLessThanOrEqual(0.05)72 })73 })7475 describe('nanoid2', () => {75 describe('customAlphabet', () => {76 it('has options', () => {77 let nanoidA = customAlphabet('a', 5)77 expect(nanoid2(5, 'a')).toEqual('aaaaa')78 expect(nanoidA()).toEqual('aaaaa')79 })8081 it('has flat distribution', () => {82 let COUNT = 100 * 100083 let LENGTH = 584 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'85 let nanoid2 = customAlphabet(ALPHABET, LENGTH)8687 let chars = { }88 for (let i = 0; i < COUNT; i++) {87 let id = nanoid2(LENGTH, ALPHABET)89 let id = nanoid2()90 for (let char of id) {91 if (!chars[char]) chars[char] = 092 chars[char] += 193 }
11 unmodified lines
105 expect(max - min).toBeLessThanOrEqual(0.05)106 })107 })108107 describe('nanoid3', () => {109 describe('customRandom', () => {110 it('supports generator', () => {111 let sequence = [2, 255, 3, 7, 7, 7, 7, 7, 0, 1]110 function customRandom (size) {112 function fakeRandom (size) {113 let bytes = []114 for (let i = 0; i < size; i += sequence.length) {115 bytes = bytes.concat(sequence.slice(0, size - i))116 }117 return bytes118 }119 let nanoid4 = customRandom('abcde', 4, fakeRandom)120 let nanoid18 = customRandom('abcde', 18, fakeRandom)117 expect(nanoid3(4, 'abcde', customRandom)).toEqual('adca')118 expect(nanoid3(18, 'abcde', customRandom)).toEqual('cbadcbadcbadcbadcc')121 expect(nanoid4()).toEqual('adca')122 expect(nanoid18()).toEqual('cbadcbadcbadcbadcc')123 })120121 it('respects size', () => {122 expect(nanoid3(4, 'abcde', random)).toHaveLength(4)123 expect(nanoid3(20, 'abcde', random)).toHaveLength(20)124 })124 })125126 describe('urlAlphabet', () => {127 it('is string', () => {
30 unmodified lines
modified:test/non-secure.test.js+6 added-4 removed
1let { nanoid, nanoid2 } = require('../non-secure')1let { nanoid, customAlphabet } = require('../non-secure')23let { urlAlphabet } = require('..')45describe('nanoid', () => {
49 unmodified lines
55 expect(max - min).toBeLessThanOrEqual(0.05)56 })57})5859describe('nanoid2', () => {59describe('customAlphabet', () => {60 it('has options', () => {61 let nanoidA = customAlphabet('a', 5)61 expect(nanoid2(5, 'a')).toEqual('aaaaa')62 expect(nanoidA()).toEqual('aaaaa')63 })6465 it('has flat distribution', () => {66 let COUNT = 100 * 100067 let LENGTH = 568 let ALPHABET = 'abcdefghijklmnopqrstuvwxyz'69 let nanoid2 = customAlphabet(ALPHABET, LENGTH)7071 let chars = { }72 for (let i = 0; i < COUNT; i++) {71 let id = nanoid2(LENGTH, ALPHABET)73 let id = nanoid2()74 for (let char of id) {75 if (!chars[char]) chars[char] = 076 chars[char] += 177 }
14 unmodified lines
modified:index.browser.js+19 added-17 removed
49 unmodified lines
50// }5152let random = bytes => self.crypto.getRandomValues(new Uint8Array(bytes))5354let nanoid3 = (size, alphabet, getRandom) => {54let customRandom = (alphabet, size, getRandom) => {55 // We can’t use bytes bigger than the alphabet. To make bytes values closer56 // to the alphabet, we apply bitmask on them. We look for the closest57 // `2 ** x - 1` number, which will be bigger than alphabet size. If we have58 // 30 symbols in the alphabet, we will take 31 (00011111).
2 unmodified lines
61 // Bitmask is not a perfect solution (in our example it will pass 31 bytes,62 // which is bigger than the alphabet). As a result, we will need more bytes,63 // than ID size, because we will refuse bytes bigger than the alphabet.6465 // Every hardware random generator call is costly,66 // because we need to wait for entropy collection. This is why often it will67 // be faster to ask for few extra bytes in advance, to avoid additional calls.65 // Every hardware random generator call is costly, because we need to wait66 // for entropy collection. This is why often it will be faster to ask for67 // few extra bytes in advance, to avoid additional calls.6869 // Here we calculate how many random bytes should we call in advance.70 // It depends on ID length, mask / alphabet size and magic number 1.671 // (which was selected according benchmarks).7273 // -~f => Math.ceil(f) if n is float number74 // -~i => i + 1 if n is integer number75 let step = -~(1.6 * mask * size / alphabet.length)76 let id = ''7677 return () => {78 let id = ''78 while (true) {79 let bytes = getRandom(step)80 // Compact alternative for `for (var j = 0; j < step; j++)`81 let j = step82 while (j--) {83 // If random byte is bigger than alphabet even after bitmask,84 // we refuse it by `|| ''`.85 id += alphabet[bytes[j] & mask] || ''86 // More compact than `id.length + 1 === size`87 if (id.length === +size) return id79 while (true) {80 let bytes = getRandom(step)81 // Compact alternative for `for (var j = 0; j < step; j++)`82 let j = step83 while (j--) {84 // If random byte is bigger than alphabet even after bitmask,85 // we refuse it by `|| ''`.86 id += alphabet[bytes[j] & mask] || ''87 // More compact than `id.length + 1 === size`88 if (id.length === +size) return id89 }90 }91 }92}9392let nanoid2 = (size, alphabet) => nanoid3(size, alphabet, random)94let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)9596let nanoid = (size = 21) => {97 let id = ''98 let bytes = self.crypto.getRandomValues(new Uint8Array(size))
20 unmodified lines
119 }120 return id121}122121module.exports = { nanoid, nanoid2, nanoid3, urlAlphabet, random }123module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
modified:index.d.ts+19 added-15 removed
20 unmodified lines
21 * will not be secure.22 *23 * @param alphabet Symbols to be used in ID.24 * @param size The number of symbols in ID. Defauls is 21.25 * @returns Random string.25 * @returns Random string generator26 *27 * ```js28 * const { nanoid2 } = require('nanoid')29 * model.id = nanoid2(5, '0123456789абвгдеё') //=> "8ё56а"28 * const { customAlphabet } = require('nanoid')29 * const nanoid = customAlphabet('0123456789абвгдеё', 5)30 * nanoid() //=> "8ё56а"31 * ```32 */32export function nanoid2 (size: number, alphabet: string): string33export function customAlphabet (alphabet: string, size: number): () => string3435/**36 * Generate unique ID with custom random generator and alphabet.37 *38 * Alphabet must contain 256 symbols or less. Otherwise, the generator39 * will not be secure.40 *41 * ```js41 * import { nanoid3 } from 'nanoid/format'42 * import { customRandom } from 'nanoid/format'43 *43 * nanoid3(5, "abcdef", size => {44 * const nanoid = customRandom("abcdef", 5, size => {45 * const random = []46 * for (let i = 0; i < size; i++) {47 * random.push(randomByte())48 * }49 * return random49 * }) //=> "fbaef"50 * })51 *52 * nanoid() //=> "fbaef"53 * ```54 *52 * @param size The number of symbols in new random string.55 * @param alphabet Symbols to be used in new random string.56 * @param size The number of symbols in new random string.57 * @param random The random bytes generator.55 * @returns Random string.58 * @returns Random string generator59 */57export function nanoid3 (58 size: number,60export function customRandom (61 alphabet: string,62 size: number,63 random: (bytes: number) => Uint8Array,61): string64): () => string6566/**67 * URL safe symbols.68 *69 * ```js70 * import { urlAlphabet } from 'nanoid'71 * const nanoid = customRandom(urlAlphabet, 10)68 * generate(10, url) //=> "Uakgb_J5m9"72 * nanoid() //=> "Uakgb_J5m9"73 * ```74 */75export const urlAlphabet: string7677/**78 * Return array with random bytes from hardware random generator.79 *80 * ```js77 * import { nanoid3, random } from 'nanoid'78 * nanoid3(5, "abcdef", random) //=> "fbaef"81 * import { customRandom, random } from 'nanoid'82 * const nanoid = customRandom("abcdef", 5, random)83 * ```84 *85 * @param bytes The size of array.86 * @returns Arrays with random bytes.
2 unmodified lines
modified:index.js+19 added-17 removed
15 unmodified lines
16 }17 return crypto.randomFillSync(buffer)18}1920let nanoid3 = (size, alphabet, getRandom) => {20let customRandom = (alphabet, size, getRandom) => {21 // We can’t use bytes bigger than the alphabet. To make bytes values closer22 // to the alphabet, we apply bitmask on them. We look for the closest23 // `2 ** x - 1` number, which will be bigger than alphabet size. If we have24 // 30 symbols in the alphabet, we will take 31 (00011111).
1 unmodified line
26 // Bitmask is not a perfect solution (in our example it will pass 31 bytes,27 // which is bigger than the alphabet). As a result, we will need more bytes,28 // than ID size, because we will refuse bytes bigger than the alphabet.2930 // Every hardware random generator call is costly,31 // because we need to wait for entropy collection. This is why often it will32 // be faster to ask for few extra bytes in advance, to avoid additional calls.30 // Every hardware random generator call is costly, because we need to wait31 // for entropy collection. This is why often it will be faster to ask for32 // few extra bytes in advance, to avoid additional calls.3334 // Here we calculate how many random bytes should we call in advance.35 // It depends on ID length, mask / alphabet size and magic number 1.636 // (which was selected according benchmarks).37 let step = Math.ceil(1.6 * mask * size / alphabet.length)38 let id = ''3839 return () => {40 let id = ''40 while (true) {41 let bytes = getRandom(step)42 // Compact alternative for `for (var i = 0; i < step; i++)`43 let i = step44 while (i--) {45 // If random byte is bigger than alphabet even after bitmask,46 // we refuse it by `|| ''`.47 id += alphabet[bytes[i] & mask] || ''48 // More compact than `id.length + 1 === size`49 if (id.length === +size) return id41 while (true) {42 let bytes = getRandom(step)43 // Compact alternative for `for (var i = 0; i < step; i++)`44 let i = step45 while (i--) {46 // If random byte is bigger than alphabet even after bitmask,47 // we refuse it by `|| ''`.48 id += alphabet[bytes[i] & mask] || ''49 // More compact than `id.length + 1 === size`50 if (id.length === +size) return id51 }52 }53 }54}5554let nanoid2 = (size, alphabet) => nanoid3(size, alphabet, random)56let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)5758let nanoid = (size = 21) => {59 let bytes = random(size)60 let id = ''
7 unmodified lines
68 }69 return id70}7170module.exports = { nanoid, nanoid2, nanoid3, urlAlphabet, random }72module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
modified:package.json+9 added-9 removed
65 unmodified lines
66 "import": "{ nanoid }",67 "limit": "110 B"68 },69 {70 "name": "nanoid2",71 "import": "{ nanoid2 }",70 "name": "customAlphabet",71 "import": "{ customAlphabet }",72 "limit": "144 B"73 },74 {75 "name": "urlAlphabet",
3 unmodified lines
79 {80 "name": "non-secure nanoid",81 "import": "{ nanoid }",82 "path": "non-secure/index.js",83 "limit": "85 B"83 "limit": "103 B"84 },85 {86 "name": "non-secure nanoid2",87 "import": "{ nanoid2 }",86 "name": "non-secure customAlphabet",87 "import": "{ customAlphabet }",88 "path": "non-secure/index.js",89 "limit": "44 B"89 "limit": "45 B"90 },91 {92 "name": "async nanoid",93 "import": "{ nanoid }",94 "path": "async/index.js",95 "limit": "120 B"96 },97 {98 "name": "async nanoid2",99 "import": "{ nanoid2 }",98 "name": "async customAlphabet",99 "import": "{ customAlphabet }",100 "path": "async/index.js",101 "limit": "130 B"101 "limit": "132 B"102 }103 ],104 "eslintConfig": {105 "extends": "@logux/eslint-config",
75 unmodified lines
modified:README.md+18 added-19 removed
322 unmodified lines
323324325### Custom Alphabet or Length326327`nanoid2` allows you to change ID’s alphabet. It has `2` in the name,328because it accepts 2 arguments (alphabet and optional size) in contrast329to `nanoid`, which accepts only 1 argument (optional size).327`customAlphabet` allows you to create `nanoid` with own alphabet and ID length.328329```js332import { nanoid2 } from 'nanoid'333model.id = nanoid2(10, '1234567890abcdef') //=> "4f90d13a42"330import { customAlphabet } from 'nanoid'331const nanoid = customAlphabet('1234567890abcdef', 10)332model.id = nanoid() //=> "4f90d13a42"333```334335Check the safety of your custom alphabet and ID length336in our [ID collision probability] calculator.
4 unmodified lines
341342Asynchronous and non-secure API is also available:343344```js346import { nanoid2 } from 'nanoid/async'345import { customAlphabet } from 'nanoid/async'346const nanoid = customAlphabet('1234567890abcdef', 10)347async function createUser () {348 user.id = await nanoid2(10, '1234567890abcdef')348 user.id = await nanoid()349}350```351352```js353import { nanoid2 } from 'nanoid/non-secure'354user.id = nanoid2(10, '1234567890abcdef')353import { customAlphabet } from 'nanoid/non-secure'354const nanoid = customAlphabet('1234567890abcdef', 10)355user.id = nanoid()356```357358[ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/359[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary360361362### Custom Random Bytes Generator363363You can replace the default safe random generator using the `nanoid3` module.364For instance, to use a seed-based generator.364`customRandom` allows you to create `nanoid` and replace the default365safe random generator. For instance, to use a seed-based generator.366366This function has `3` in the name, because it accepts 3 arguments367(generator, alphabet and size).368367```js370import { nanoid3 } from 'nanoid`368import { customRandom } from 'nanoid`369370function random (size) {371 const result = []372 for (let i = 0; i < size; i++) {
1 unmodified line
374 }375 return result376}377378const nanoid = customRandom('abcdef', 10, random)380nanoid3(10, 'abcdef', random) //=> "fbaefaadeb"379nanoid() //=> "fbaefaadeb"380```381382`random` callback must accept the array size and return an array383with random numbers.
1 unmodified line
385If you want to use the same URL-friendly symbols with `nanoid3`,386you can get the default alphabet from the `urlAlphabet`.387388```js390const { nanoid3, urlAlphabet } = require('nanoid')391nanoid3(10, urlAlphabet, random) //=> "93ce_Ltuub"389const { customRandom, urlAlphabet } = require('nanoid')390const nanoid = customRandom(urlAlphabet, 10, random)391```392394Asynchronous and non-secure APIs are not available for `nanoid3`.393Asynchronous and non-secure APIs are not available for `customRandom`.