nanoid 3.3.7 → 3.3.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -35,5 +35,520 @@ Supports modern browsers, IE [with Babel], Node.js and React Native.
35
35
  alt="Sponsored by Evil Martians" width="236" height="54">
36
36
  </a>
37
37
 
38
- ## Docs
39
- Read full docs **[here](https://github.com/ai/nanoid#readme)**.
38
+ ## Table of Contents
39
+
40
+ * [Comparison with UUID](#comparison-with-uuid)
41
+ * [Benchmark](#benchmark)
42
+ * [Security](#security)
43
+ * [API](#api)
44
+ * [Blocking](#blocking)
45
+ * [Async](#async)
46
+ * [Non-Secure](#non-secure)
47
+ * [Custom Alphabet or Size](#custom-alphabet-or-size)
48
+ * [Custom Random Bytes Generator](#custom-random-bytes-generator)
49
+ * [Usage](#usage)
50
+ * [IE](#ie)
51
+ * [React](#react)
52
+ * [React Native](#react-native)
53
+ * [Rollup](#rollup)
54
+ * [PouchDB and CouchDB](#pouchdb-and-couchdb)
55
+ * [Mongoose](#mongoose)
56
+ * [Web Workers](#web-workers)
57
+ * [CLI](#cli)
58
+ * [Other Programming Languages](#other-programming-languages)
59
+ * [Tools](#tools)
60
+
61
+
62
+ ## Comparison with UUID
63
+
64
+ Nano ID is quite comparable to UUID v4 (random-based).
65
+ It has a similar number of random bits in the ID
66
+ (126 in Nano ID and 122 in UUID), so it has a similar collision probability:
67
+
68
+ > For there to be a one in a billion chance of duplication,
69
+ > 103 trillion version 4 IDs must be generated.
70
+
71
+ There are three main differences between Nano ID and UUID v4:
72
+
73
+ 1. Nano ID uses a bigger alphabet, so a similar number of random bits
74
+ are packed in just 21 symbols instead of 36.
75
+ 2. Nano ID code is **4 times less** than `uuid/v4` package:
76
+ 130 bytes instead of 483.
77
+ 3. Because of memory allocation tricks, Nano ID is **2 times** faster than UUID.
78
+
79
+
80
+ ## Benchmark
81
+
82
+ ```rust
83
+ $ node ./test/benchmark.js
84
+ crypto.randomUUID 25,603,857 ops/sec
85
+ @napi-rs/uuid 9,973,819 ops/sec
86
+ uid/secure 8,234,798 ops/sec
87
+ @lukeed/uuid 7,464,706 ops/sec
88
+ nanoid 5,616,592 ops/sec
89
+ customAlphabet 3,115,207 ops/sec
90
+ uuid v4 1,535,753 ops/sec
91
+ secure-random-string 388,226 ops/sec
92
+ uid-safe.sync 363,489 ops/sec
93
+ cuid 187,343 ops/sec
94
+ shortid 45,758 ops/sec
95
+
96
+ Async:
97
+ nanoid/async 96,094 ops/sec
98
+ async customAlphabet 97,184 ops/sec
99
+ async secure-random-string 92,794 ops/sec
100
+ uid-safe 90,684 ops/sec
101
+
102
+ Non-secure:
103
+ uid 67,376,692 ops/sec
104
+ nanoid/non-secure 2,849,639 ops/sec
105
+ rndm 2,674,806 ops/sec
106
+ ```
107
+
108
+ Test configuration: ThinkPad X1 Carbon Gen 9, Fedora 34, Node.js 16.10.
109
+
110
+
111
+ ## Security
112
+
113
+ *See a good article about random generators theory:
114
+ [Secure random values (in Node.js)]*
115
+
116
+ * **Unpredictability.** Instead of using the unsafe `Math.random()`, Nano ID
117
+ uses the `crypto` module in Node.js and the Web Crypto API in browsers.
118
+ These modules use unpredictable hardware random generator.
119
+ * **Uniformity.** `random % alphabet` is a popular mistake to make when coding
120
+ an ID generator. The distribution will not be even; there will be a lower
121
+ chance for some symbols to appear compared to others. So, it will reduce
122
+ the number of tries when brute-forcing. Nano ID uses a [better algorithm]
123
+ and is tested for uniformity.
124
+
125
+ <img src="img/distribution.png" alt="Nano ID uniformity"
126
+ width="340" height="135">
127
+
128
+ * **Well-documented:** all Nano ID hacks are documented. See comments
129
+ in [the source].
130
+ * **Vulnerabilities:** to report a security vulnerability, please use
131
+ the [Tidelift security contact](https://tidelift.com/security).
132
+ Tidelift will coordinate the fix and disclosure.
133
+
134
+ [Secure random values (in Node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba
135
+ [better algorithm]: https://github.com/ai/nanoid/blob/main/index.js
136
+ [the source]: https://github.com/ai/nanoid/blob/main/index.js
137
+
138
+
139
+ ## Install
140
+
141
+ ```bash
142
+ npm install --save nanoid
143
+ ```
144
+
145
+ For quick hacks, you can load Nano ID from CDN. Though, it is not recommended
146
+ to be used in production because of the lower loading performance.
147
+
148
+ ```js
149
+ import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
150
+ ```
151
+
152
+ Nano ID provides ES modules. You do not need to do anything to use Nano ID
153
+ as ESM in webpack, Rollup, Parcel, or Node.js.
154
+
155
+ ```js
156
+ import { nanoid } from 'nanoid'
157
+ ```
158
+
159
+ In Node.js you can use CommonJS import:
160
+
161
+ ```js
162
+ const { nanoid } = require('nanoid')
163
+ ```
164
+
165
+
166
+ ## API
167
+
168
+ Nano ID has 3 APIs: normal (blocking), asynchronous, and non-secure.
169
+
170
+ By default, Nano ID uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID
171
+ with 21 characters (to have a collision probability similar to UUID v4).
172
+
173
+
174
+ ### Blocking
175
+
176
+ The safe and easiest way to use Nano ID.
177
+
178
+ In rare cases could block CPU from other work while noise collection
179
+ for hardware random generator.
180
+
181
+ ```js
182
+ import { nanoid } from 'nanoid'
183
+ model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT"
184
+ ```
185
+
186
+ If you want to reduce the ID size (and increase collisions probability),
187
+ you can pass the size as an argument.
188
+
189
+ ```js
190
+ nanoid(10) //=> "IRFa-VaY2b"
191
+ ```
192
+
193
+ Don’t forget to check the safety of your ID size
194
+ in our [ID collision probability] calculator.
195
+
196
+ You can also use a [custom alphabet](#custom-alphabet-or-size)
197
+ or a [random generator](#custom-random-bytes-generator).
198
+
199
+ [ID collision probability]: https://zelark.github.io/nano-id-cc/
200
+
201
+
202
+ ### Async
203
+
204
+ To generate hardware random bytes, CPU collects electromagnetic noise.
205
+ For most cases, entropy will be already collected.
206
+
207
+ In the synchronous API during the noise collection, the CPU is busy and
208
+ cannot do anything useful (for instance, process another HTTP request).
209
+
210
+ Using the asynchronous API of Nano ID, another code can run during
211
+ the entropy collection.
212
+
213
+ ```js
214
+ import { nanoid } from 'nanoid/async'
215
+
216
+ async function createUser () {
217
+ user.id = await nanoid()
218
+ }
219
+ ```
220
+
221
+ Read more about entropy collection in [`crypto.randomBytes`] docs.
222
+
223
+ Unfortunately, you will lose Web Crypto API advantages in a browser
224
+ if you use the asynchronous API. So, currently, in the browser, you are limited
225
+ with either security (`nanoid`), asynchronous behavior (`nanoid/async`),
226
+ or non-secure behavior (`nanoid/non-secure`) that will be explained
227
+ in the next part of the documentation.
228
+
229
+ [`crypto.randomBytes`]: https://nodejs.org/api/crypto.html#crypto_crypto_randombytes_size_callback
230
+
231
+
232
+ ### Non-Secure
233
+
234
+ By default, Nano ID uses hardware random bytes generation for security
235
+ and low collision probability. If you are not so concerned with security,
236
+ you can use the faster non-secure generator.
237
+
238
+ ```js
239
+ import { nanoid } from 'nanoid/non-secure'
240
+ const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
241
+ ```
242
+
243
+
244
+ ### Custom Alphabet or Size
245
+
246
+ `customAlphabet` allows you to create `nanoid` with your own alphabet
247
+ and ID size.
248
+
249
+ ```js
250
+ import { customAlphabet } from 'nanoid'
251
+ const nanoid = customAlphabet('1234567890abcdef', 10)
252
+ model.id = nanoid() //=> "4f90d13a42"
253
+ ```
254
+
255
+ ```js
256
+ import { customAlphabet } from 'nanoid/async'
257
+ const nanoid = customAlphabet('1234567890abcdef', 10)
258
+ async function createUser () {
259
+ user.id = await nanoid()
260
+ }
261
+ ```
262
+
263
+ ```js
264
+ import { customAlphabet } from 'nanoid/non-secure'
265
+ const nanoid = customAlphabet('1234567890abcdef', 10)
266
+ user.id = nanoid()
267
+ ```
268
+
269
+ Check the safety of your custom alphabet and ID size in our
270
+ [ID collision probability] calculator. For more alphabets, check out the options
271
+ in [`nanoid-dictionary`].
272
+
273
+ Alphabet must contain 256 symbols or less.
274
+ Otherwise, the security of the internal generator algorithm is not guaranteed.
275
+
276
+ In addition to setting a default size, you can change the ID size when calling
277
+ the function:
278
+
279
+ ```js
280
+ import { customAlphabet } from 'nanoid'
281
+ const nanoid = customAlphabet('1234567890abcdef', 10)
282
+ model.id = nanoid(5) //=> "f01a2"
283
+ ```
284
+
285
+ [ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/
286
+ [`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary
287
+
288
+
289
+ ### Custom Random Bytes Generator
290
+
291
+ `customRandom` allows you to create a `nanoid` and replace alphabet
292
+ and the default random bytes generator.
293
+
294
+ In this example, a seed-based generator is used:
295
+
296
+ ```js
297
+ import { customRandom } from 'nanoid'
298
+
299
+ const rng = seedrandom(seed)
300
+ const nanoid = customRandom('abcdef', 10, size => {
301
+ return (new Uint8Array(size)).map(() => 256 * rng())
302
+ })
303
+
304
+ nanoid() //=> "fbaefaadeb"
305
+ ```
306
+
307
+ `random` callback must accept the array size and return an array
308
+ with random numbers.
309
+
310
+ If you want to use the same URL-friendly symbols with `customRandom`,
311
+ you can get the default alphabet using the `urlAlphabet`.
312
+
313
+ ```js
314
+ const { customRandom, urlAlphabet } = require('nanoid')
315
+ const nanoid = customRandom(urlAlphabet, 10, random)
316
+ ```
317
+
318
+ Asynchronous and non-secure APIs are not available for `customRandom`.
319
+
320
+ Note, that between Nano ID versions we may change random generator
321
+ call sequence. If you are using seed-based generators, we do not guarantee
322
+ the same result.
323
+
324
+
325
+ ## Usage
326
+
327
+ ### IE
328
+
329
+ If you support IE, you need to [transpile `node_modules`] by Babel
330
+ and add `crypto` alias. Moreover, `UInt8Array` in IE actually
331
+ is not an array and to cope with it, you have to convert it to an array
332
+ manually:
333
+
334
+ ```js
335
+ // polyfills.js
336
+ if (!window.crypto && window.msCrypto) {
337
+ window.crypto = window.msCrypto
338
+
339
+ const getRandomValuesDef = window.crypto.getRandomValues
340
+
341
+ window.crypto.getRandomValues = function (array) {
342
+ const values = getRandomValuesDef.call(window.crypto, array)
343
+ const result = []
344
+
345
+ for (let i = 0; i < array.length; i++) {
346
+ result[i] = values[i];
347
+ }
348
+
349
+ return result
350
+ };
351
+ }
352
+ ```
353
+
354
+ ```js
355
+ import './polyfills.js'
356
+ import { nanoid } from 'nanoid'
357
+ ```
358
+
359
+ [transpile `node_modules`]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
360
+
361
+
362
+ ### React
363
+
364
+ There’s no correct way to use Nano ID for React `key` prop
365
+ since it should be consistent among renders.
366
+
367
+ ```jsx
368
+ function Todos({todos}) {
369
+ return (
370
+ <ul>
371
+ {todos.map(todo => (
372
+ <li key={nanoid()}> /* DON’T DO IT */
373
+ {todo.text}
374
+ </li>
375
+ ))}
376
+ </ul>
377
+ )
378
+ }
379
+ ```
380
+
381
+ You should rather try to reach for stable ID inside your list item.
382
+
383
+ ```jsx
384
+ const todoItems = todos.map((todo) =>
385
+ <li key={todo.id}>
386
+ {todo.text}
387
+ </li>
388
+ )
389
+ ```
390
+
391
+ In case you don’t have stable IDs you'd rather use index as `key`
392
+ instead of `nanoid()`:
393
+
394
+ ```jsx
395
+ const todoItems = todos.map((text, index) =>
396
+ <li key={index}> /* Still not recommended but preferred over nanoid().
397
+ Only do this if items have no stable IDs. */
398
+ {text}
399
+ </li>
400
+ )
401
+ ```
402
+
403
+
404
+ ### React Native
405
+
406
+ React Native does not have built-in random generator. The following polyfill
407
+ works for plain React Native and Expo starting with `39.x`.
408
+
409
+ 1. Check [`react-native-get-random-values`] docs and install it.
410
+ 2. Import it before Nano ID.
411
+
412
+ ```js
413
+ import 'react-native-get-random-values'
414
+ import { nanoid } from 'nanoid'
415
+ ```
416
+
417
+ [`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values
418
+
419
+
420
+ ### Rollup
421
+
422
+ For Rollup you will need [`@rollup/plugin-node-resolve`] to bundle browser version
423
+ of this library.:
424
+
425
+ ```js
426
+ plugins: [
427
+ nodeResolve({
428
+ browser: true
429
+ })
430
+ ]
431
+ ```
432
+
433
+ [`@rollup/plugin-node-resolve`]: https://github.com/rollup/plugins/tree/master/packages/node-resolve
434
+
435
+
436
+ ### PouchDB and CouchDB
437
+
438
+ In PouchDB and CouchDB, IDs can’t start with an underscore `_`.
439
+ A prefix is required to prevent this issue, as Nano ID might use a `_`
440
+ at the start of the ID by default.
441
+
442
+ Override the default ID with the following option:
443
+
444
+ ```js
445
+ db.put({
446
+ _id: 'id' + nanoid(),
447
+
448
+ })
449
+ ```
450
+
451
+
452
+ ### Mongoose
453
+
454
+ ```js
455
+ const mySchema = new Schema({
456
+ _id: {
457
+ type: String,
458
+ default: () => nanoid()
459
+ }
460
+ })
461
+ ```
462
+
463
+
464
+ ### Web Workers
465
+
466
+ Web Workers do not have access to a secure random generator.
467
+
468
+ Security is important in IDs when IDs should be unpredictable.
469
+ For instance, in "access by URL" link generation.
470
+ If you do not need unpredictable IDs, but you need to use Web Workers,
471
+ you can use the non‑secure ID generator.
472
+
473
+ ```js
474
+ import { nanoid } from 'nanoid/non-secure'
475
+ nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
476
+ ```
477
+
478
+ Note: non-secure IDs are more prone to collision attacks.
479
+
480
+
481
+ ### CLI
482
+
483
+ You can get unique ID in terminal by calling `npx nanoid`. You need only
484
+ Node.js in the system. You do not need Nano ID to be installed anywhere.
485
+
486
+ ```sh
487
+ $ npx nanoid
488
+ npx: installed 1 in 0.63s
489
+ LZfXLFzPPR4NNrgjlWDxn
490
+ ```
491
+
492
+ Size of generated ID can be specified with `--size` (or `-s`) option:
493
+
494
+ ```sh
495
+ $ npx nanoid --size 10
496
+ L3til0JS4z
497
+ ```
498
+
499
+ Custom alphabet can be specified with `--alphabet` (or `-a`) option
500
+ (note that in this case `--size` is required):
501
+
502
+ ```sh
503
+ $ npx nanoid --alphabet abc --size 15
504
+ bccbcabaabaccab
505
+ ```
506
+
507
+ ### Other Programming Languages
508
+
509
+ Nano ID was ported to many languages. You can use these ports to have
510
+ the same ID generator on the client and server side.
511
+
512
+ * [C#](https://github.com/codeyu/nanoid-net)
513
+ * [C++](https://github.com/mcmikecreations/nanoid_cpp)
514
+ * [Clojure and ClojureScript](https://github.com/zelark/nano-id)
515
+ * [ColdFusion/CFML](https://github.com/JamoCA/cfml-nanoid)
516
+ * [Crystal](https://github.com/mamantoha/nanoid.cr)
517
+ * [Dart & Flutter](https://github.com/pd4d10/nanoid-dart)
518
+ * [Deno](https://github.com/ianfabs/nanoid)
519
+ * [Go](https://github.com/matoous/go-nanoid)
520
+ * [Elixir](https://github.com/railsmechanic/nanoid)
521
+ * [Haskell](https://github.com/MichelBoucey/NanoID)
522
+ * [Janet](https://sr.ht/~statianzo/janet-nanoid/)
523
+ * [Java](https://github.com/aventrix/jnanoid)
524
+ * [Nim](https://github.com/icyphox/nanoid.nim)
525
+ * [OCaml](https://github.com/routineco/ocaml-nanoid)
526
+ * [Perl](https://github.com/tkzwtks/Nanoid-perl)
527
+ * [PHP](https://github.com/hidehalo/nanoid-php)
528
+ * [Python](https://github.com/puyuan/py-nanoid)
529
+ with [dictionaries](https://pypi.org/project/nanoid-dictionary)
530
+ * [Postgres Extension](https://github.com/spa5k/uids-postgres)
531
+ * [R](https://github.com/hrbrmstr/nanoid) (with dictionaries)
532
+ * [Ruby](https://github.com/radeno/nanoid.rb)
533
+ * [Rust](https://github.com/nikolay-govorov/nanoid)
534
+ * [Swift](https://github.com/antiflasher/NanoID)
535
+ * [Unison](https://share.unison-lang.org/latest/namespaces/hojberg/nanoid)
536
+ * [V](https://github.com/invipal/nanoid)
537
+ * [Zig](https://github.com/SasLuca/zig-nanoid)
538
+
539
+ For other environments, [CLI] is available to generate IDs from a command line.
540
+
541
+ [CLI]: #cli
542
+
543
+
544
+ ## Tools
545
+
546
+ * [ID size calculator] shows collision probability when adjusting
547
+ the ID alphabet or size.
548
+ * [`nanoid-dictionary`] with popular alphabets to use with [`customAlphabet`].
549
+ * [`nanoid-good`] to be sure that your ID doesn’t contain any obscene words.
550
+
551
+ [`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary
552
+ [ID size calculator]: https://zelark.github.io/nano-id-cc/
553
+ [`customAlphabet`]: #custom-alphabet-or-size
554
+ [`nanoid-good`]: https://github.com/y-gagar1n/nanoid-good
@@ -1,27 +1,61 @@
1
1
  let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
2
+
2
3
  let customAlphabet = (alphabet, defaultSize = 21) => {
4
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
5
+ // values closer to the alphabet size. The bitmask calculates the closest
6
+ // `2^31 - 1` number, which exceeds the alphabet size.
7
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
8
+ // `Math.clz32` is not used, because it is not available in browsers.
3
9
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
10
+ // Though, the bitmask solution is not perfect since the bytes exceeding
11
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
12
+ // the random bytes redundancy has to be satisfied.
13
+
14
+ // Note: every hardware random generator call is performance expensive,
15
+ // because the system call for entropy collection takes a lot of time.
16
+ // So, to avoid additional system calls, extra bytes are requested in advance.
17
+
18
+ // Next, a step determines how many random bytes to generate.
19
+ // The number of random bytes gets decided upon the ID size, mask,
20
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
21
+ // according to benchmarks).
22
+
23
+ // `-~f => Math.ceil(f)` if f is a float
24
+ // `-~i => i + 1` if i is an integer
4
25
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
26
+
5
27
  return async (size = defaultSize) => {
6
28
  let id = ''
7
29
  while (true) {
8
30
  let bytes = crypto.getRandomValues(new Uint8Array(step))
9
- let i = step
31
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
32
+ let i = step | 0
10
33
  while (i--) {
34
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
11
35
  id += alphabet[bytes[i] & mask] || ''
12
36
  if (id.length === size) return id
13
37
  }
14
38
  }
15
39
  }
16
40
  }
41
+
17
42
  let nanoid = async (size = 21) => {
18
43
  let id = ''
19
- let bytes = crypto.getRandomValues(new Uint8Array(size))
44
+ let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
45
+
46
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
20
47
  while (size--) {
48
+ // It is incorrect to use bytes exceeding the alphabet size.
49
+ // The following mask reduces the random byte in the 0-255 value
50
+ // range to the 0-63 value range. Therefore, adding hacks, such
51
+ // as empty string fallback or magic numbers, is unneccessary because
52
+ // the bitmask trims bytes down to the alphabet size.
21
53
  let byte = bytes[size] & 63
22
54
  if (byte < 36) {
55
+ // `0-9a-z`
23
56
  id += byte.toString(36)
24
57
  } else if (byte < 62) {
58
+ // `A-Z`
25
59
  id += (byte - 26).toString(36).toUpperCase()
26
60
  } else if (byte < 63) {
27
61
  id += '_'
@@ -31,4 +65,5 @@ let nanoid = async (size = 21) => {
31
65
  }
32
66
  return id
33
67
  }
68
+
34
69
  module.exports = { nanoid, customAlphabet, random }
@@ -1,27 +1,61 @@
1
1
  let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
2
+
2
3
  let customAlphabet = (alphabet, defaultSize = 21) => {
4
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
5
+ // values closer to the alphabet size. The bitmask calculates the closest
6
+ // `2^31 - 1` number, which exceeds the alphabet size.
7
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
8
+ // `Math.clz32` is not used, because it is not available in browsers.
3
9
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
10
+ // Though, the bitmask solution is not perfect since the bytes exceeding
11
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
12
+ // the random bytes redundancy has to be satisfied.
13
+
14
+ // Note: every hardware random generator call is performance expensive,
15
+ // because the system call for entropy collection takes a lot of time.
16
+ // So, to avoid additional system calls, extra bytes are requested in advance.
17
+
18
+ // Next, a step determines how many random bytes to generate.
19
+ // The number of random bytes gets decided upon the ID size, mask,
20
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
21
+ // according to benchmarks).
22
+
23
+ // `-~f => Math.ceil(f)` if f is a float
24
+ // `-~i => i + 1` if i is an integer
4
25
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
26
+
5
27
  return async (size = defaultSize) => {
6
28
  let id = ''
7
29
  while (true) {
8
30
  let bytes = crypto.getRandomValues(new Uint8Array(step))
9
- let i = step
31
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
32
+ let i = step | 0
10
33
  while (i--) {
34
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
11
35
  id += alphabet[bytes[i] & mask] || ''
12
36
  if (id.length === size) return id
13
37
  }
14
38
  }
15
39
  }
16
40
  }
41
+
17
42
  let nanoid = async (size = 21) => {
18
43
  let id = ''
19
- let bytes = crypto.getRandomValues(new Uint8Array(size))
44
+ let bytes = crypto.getRandomValues(new Uint8Array((size |= 0)))
45
+
46
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
20
47
  while (size--) {
48
+ // It is incorrect to use bytes exceeding the alphabet size.
49
+ // The following mask reduces the random byte in the 0-255 value
50
+ // range to the 0-63 value range. Therefore, adding hacks, such
51
+ // as empty string fallback or magic numbers, is unneccessary because
52
+ // the bitmask trims bytes down to the alphabet size.
21
53
  let byte = bytes[size] & 63
22
54
  if (byte < 36) {
55
+ // `0-9a-z`
23
56
  id += byte.toString(36)
24
57
  } else if (byte < 62) {
58
+ // `A-Z`
25
59
  id += (byte - 26).toString(36).toUpperCase()
26
60
  } else if (byte < 63) {
27
61
  id += '_'
@@ -31,4 +65,5 @@ let nanoid = async (size = 21) => {
31
65
  }
32
66
  return id
33
67
  }
68
+
34
69
  export { nanoid, customAlphabet, random }
package/async/index.cjs CHANGED
@@ -1,7 +1,14 @@
1
1
  let crypto = require('crypto')
2
+
2
3
  let { urlAlphabet } = require('../url-alphabet/index.cjs')
4
+
5
+ // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
6
+ // because it is possible to use in combination with `Buffer.allocUnsafe()`.
3
7
  let random = bytes =>
4
8
  new Promise((resolve, reject) => {
9
+ // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
10
+ // Memory flushing is unnecessary since the buffer allocation itself resets
11
+ // the memory with the new bytes.
5
12
  crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
6
13
  if (err) {
7
14
  reject(err)
@@ -10,26 +17,55 @@ let random = bytes =>
10
17
  }
11
18
  })
12
19
  })
20
+
13
21
  let customAlphabet = (alphabet, defaultSize = 21) => {
22
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
23
+ // values closer to the alphabet size. The bitmask calculates the closest
24
+ // `2^31 - 1` number, which exceeds the alphabet size.
25
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
14
26
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
27
+ // Though, the bitmask solution is not perfect since the bytes exceeding
28
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
29
+ // the random bytes redundancy has to be satisfied.
30
+
31
+ // Note: every hardware random generator call is performance expensive,
32
+ // because the system call for entropy collection takes a lot of time.
33
+ // So, to avoid additional system calls, extra bytes are requested in advance.
34
+
35
+ // Next, a step determines how many random bytes to generate.
36
+ // The number of random bytes gets decided upon the ID size, mask,
37
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
38
+ // according to benchmarks).
15
39
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
40
+
16
41
  let tick = (id, size = defaultSize) =>
17
42
  random(step).then(bytes => {
43
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
18
44
  let i = step
19
45
  while (i--) {
46
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
20
47
  id += alphabet[bytes[i] & mask] || ''
21
- if (id.length === size) return id
48
+ if (id.length >= size) return id
22
49
  }
23
50
  return tick(id, size)
24
51
  })
52
+
25
53
  return size => tick('', size)
26
54
  }
55
+
27
56
  let nanoid = (size = 21) =>
28
- random(size).then(bytes => {
57
+ random((size |= 0)).then(bytes => {
29
58
  let id = ''
59
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
30
60
  while (size--) {
61
+ // It is incorrect to use bytes exceeding the alphabet size.
62
+ // The following mask reduces the random byte in the 0-255 value
63
+ // range to the 0-63 value range. Therefore, adding hacks, such
64
+ // as empty string fallback or magic numbers, is unneccessary because
65
+ // the bitmask trims bytes down to the alphabet size.
31
66
  id += urlAlphabet[bytes[size] & 63]
32
67
  }
33
68
  return id
34
69
  })
70
+
35
71
  module.exports = { nanoid, customAlphabet, random }
package/async/index.js CHANGED
@@ -1,7 +1,14 @@
1
1
  import crypto from 'crypto'
2
+
2
3
  import { urlAlphabet } from '../url-alphabet/index.js'
4
+
5
+ // `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
6
+ // because it is possible to use in combination with `Buffer.allocUnsafe()`.
3
7
  let random = bytes =>
4
8
  new Promise((resolve, reject) => {
9
+ // `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
10
+ // Memory flushing is unnecessary since the buffer allocation itself resets
11
+ // the memory with the new bytes.
5
12
  crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
6
13
  if (err) {
7
14
  reject(err)
@@ -10,26 +17,55 @@ let random = bytes =>
10
17
  }
11
18
  })
12
19
  })
20
+
13
21
  let customAlphabet = (alphabet, defaultSize = 21) => {
22
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
23
+ // values closer to the alphabet size. The bitmask calculates the closest
24
+ // `2^31 - 1` number, which exceeds the alphabet size.
25
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
14
26
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
27
+ // Though, the bitmask solution is not perfect since the bytes exceeding
28
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
29
+ // the random bytes redundancy has to be satisfied.
30
+
31
+ // Note: every hardware random generator call is performance expensive,
32
+ // because the system call for entropy collection takes a lot of time.
33
+ // So, to avoid additional system calls, extra bytes are requested in advance.
34
+
35
+ // Next, a step determines how many random bytes to generate.
36
+ // The number of random bytes gets decided upon the ID size, mask,
37
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
38
+ // according to benchmarks).
15
39
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
40
+
16
41
  let tick = (id, size = defaultSize) =>
17
42
  random(step).then(bytes => {
43
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
18
44
  let i = step
19
45
  while (i--) {
46
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
20
47
  id += alphabet[bytes[i] & mask] || ''
21
- if (id.length === size) return id
48
+ if (id.length >= size) return id
22
49
  }
23
50
  return tick(id, size)
24
51
  })
52
+
25
53
  return size => tick('', size)
26
54
  }
55
+
27
56
  let nanoid = (size = 21) =>
28
- random(size).then(bytes => {
57
+ random((size |= 0)).then(bytes => {
29
58
  let id = ''
59
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
30
60
  while (size--) {
61
+ // It is incorrect to use bytes exceeding the alphabet size.
62
+ // The following mask reduces the random byte in the 0-255 value
63
+ // range to the 0-63 value range. Therefore, adding hacks, such
64
+ // as empty string fallback or magic numbers, is unneccessary because
65
+ // the bitmask trims bytes down to the alphabet size.
31
66
  id += urlAlphabet[bytes[size] & 63]
32
67
  }
33
68
  return id
34
69
  })
70
+
35
71
  export { nanoid, customAlphabet, random }
@@ -1,26 +1,57 @@
1
1
  import { getRandomBytesAsync } from 'expo-random'
2
+
2
3
  import { urlAlphabet } from '../url-alphabet/index.js'
4
+
3
5
  let random = getRandomBytesAsync
6
+
4
7
  let customAlphabet = (alphabet, defaultSize = 21) => {
8
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
9
+ // values closer to the alphabet size. The bitmask calculates the closest
10
+ // `2^31 - 1` number, which exceeds the alphabet size.
11
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
5
12
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
13
+ // Though, the bitmask solution is not perfect since the bytes exceeding
14
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
15
+ // the random bytes redundancy has to be satisfied.
16
+
17
+ // Note: every hardware random generator call is performance expensive,
18
+ // because the system call for entropy collection takes a lot of time.
19
+ // So, to avoid additional system calls, extra bytes are requested in advance.
20
+
21
+ // Next, a step determines how many random bytes to generate.
22
+ // The number of random bytes gets decided upon the ID size, mask,
23
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
24
+ // according to benchmarks).
6
25
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
26
+
7
27
  let tick = (id, size = defaultSize) =>
8
28
  random(step).then(bytes => {
29
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
9
30
  let i = step
10
31
  while (i--) {
32
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
11
33
  id += alphabet[bytes[i] & mask] || ''
12
- if (id.length === size) return id
34
+ if (id.length >= size) return id
13
35
  }
14
36
  return tick(id, size)
15
37
  })
38
+
16
39
  return size => tick('', size)
17
40
  }
41
+
18
42
  let nanoid = (size = 21) =>
19
- random(size).then(bytes => {
43
+ random((size |= 0)).then(bytes => {
20
44
  let id = ''
45
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
21
46
  while (size--) {
47
+ // It is incorrect to use bytes exceeding the alphabet size.
48
+ // The following mask reduces the random byte in the 0-255 value
49
+ // range to the 0-63 value range. Therefore, adding hacks, such
50
+ // as empty string fallback or magic numbers, is unneccessary because
51
+ // the bitmask trims bytes down to the alphabet size.
22
52
  id += urlAlphabet[bytes[size] & 63]
23
53
  }
24
54
  return id
25
55
  })
56
+
26
57
  export { nanoid, customAlphabet, random }
package/index.browser.cjs CHANGED
@@ -1,28 +1,65 @@
1
+ // This file replaces `index.js` in bundlers like webpack or Rollup,
2
+ // according to `browser` config in `package.json`.
3
+
1
4
  let { urlAlphabet } = require('./url-alphabet/index.cjs')
5
+
2
6
  let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
7
+
3
8
  let customRandom = (alphabet, defaultSize, getRandom) => {
9
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
10
+ // values closer to the alphabet size. The bitmask calculates the closest
11
+ // `2^31 - 1` number, which exceeds the alphabet size.
12
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
13
+ // `Math.clz32` is not used, because it is not available in browsers.
4
14
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
15
+ // Though, the bitmask solution is not perfect since the bytes exceeding
16
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
17
+ // the random bytes redundancy has to be satisfied.
18
+
19
+ // Note: every hardware random generator call is performance expensive,
20
+ // because the system call for entropy collection takes a lot of time.
21
+ // So, to avoid additional system calls, extra bytes are requested in advance.
22
+
23
+ // Next, a step determines how many random bytes to generate.
24
+ // The number of random bytes gets decided upon the ID size, mask,
25
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
26
+ // according to benchmarks).
27
+
28
+ // `-~f => Math.ceil(f)` if f is a float
29
+ // `-~i => i + 1` if i is an integer
5
30
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
31
+
6
32
  return (size = defaultSize) => {
7
33
  let id = ''
8
34
  while (true) {
9
35
  let bytes = getRandom(step)
10
- let j = step
36
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
37
+ let j = step | 0
11
38
  while (j--) {
39
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
12
40
  id += alphabet[bytes[j] & mask] || ''
13
41
  if (id.length === size) return id
14
42
  }
15
43
  }
16
44
  }
17
45
  }
46
+
18
47
  let customAlphabet = (alphabet, size = 21) =>
19
48
  customRandom(alphabet, size, random)
49
+
20
50
  let nanoid = (size = 21) =>
21
51
  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
52
+ // It is incorrect to use bytes exceeding the alphabet size.
53
+ // The following mask reduces the random byte in the 0-255 value
54
+ // range to the 0-63 value range. Therefore, adding hacks, such
55
+ // as empty string fallback or magic numbers, is unneccessary because
56
+ // the bitmask trims bytes down to the alphabet size.
22
57
  byte &= 63
23
58
  if (byte < 36) {
59
+ // `0-9a-z`
24
60
  id += byte.toString(36)
25
61
  } else if (byte < 62) {
62
+ // `A-Z`
26
63
  id += (byte - 26).toString(36).toUpperCase()
27
64
  } else if (byte > 62) {
28
65
  id += '-'
@@ -31,4 +68,5 @@ let nanoid = (size = 21) =>
31
68
  }
32
69
  return id
33
70
  }, '')
71
+
34
72
  module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
package/index.browser.js CHANGED
@@ -1,28 +1,65 @@
1
+ // This file replaces `index.js` in bundlers like webpack or Rollup,
2
+ // according to `browser` config in `package.json`.
3
+
1
4
  import { urlAlphabet } from './url-alphabet/index.js'
5
+
2
6
  let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
7
+
3
8
  let customRandom = (alphabet, defaultSize, getRandom) => {
9
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
10
+ // values closer to the alphabet size. The bitmask calculates the closest
11
+ // `2^31 - 1` number, which exceeds the alphabet size.
12
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
13
+ // `Math.clz32` is not used, because it is not available in browsers.
4
14
  let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
15
+ // Though, the bitmask solution is not perfect since the bytes exceeding
16
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
17
+ // the random bytes redundancy has to be satisfied.
18
+
19
+ // Note: every hardware random generator call is performance expensive,
20
+ // because the system call for entropy collection takes a lot of time.
21
+ // So, to avoid additional system calls, extra bytes are requested in advance.
22
+
23
+ // Next, a step determines how many random bytes to generate.
24
+ // The number of random bytes gets decided upon the ID size, mask,
25
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
26
+ // according to benchmarks).
27
+
28
+ // `-~f => Math.ceil(f)` if f is a float
29
+ // `-~i => i + 1` if i is an integer
5
30
  let step = -~((1.6 * mask * defaultSize) / alphabet.length)
31
+
6
32
  return (size = defaultSize) => {
7
33
  let id = ''
8
34
  while (true) {
9
35
  let bytes = getRandom(step)
10
- let j = step
36
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
37
+ let j = step | 0
11
38
  while (j--) {
39
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
12
40
  id += alphabet[bytes[j] & mask] || ''
13
41
  if (id.length === size) return id
14
42
  }
15
43
  }
16
44
  }
17
45
  }
46
+
18
47
  let customAlphabet = (alphabet, size = 21) =>
19
48
  customRandom(alphabet, size, random)
49
+
20
50
  let nanoid = (size = 21) =>
21
51
  crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
52
+ // It is incorrect to use bytes exceeding the alphabet size.
53
+ // The following mask reduces the random byte in the 0-255 value
54
+ // range to the 0-63 value range. Therefore, adding hacks, such
55
+ // as empty string fallback or magic numbers, is unneccessary because
56
+ // the bitmask trims bytes down to the alphabet size.
22
57
  byte &= 63
23
58
  if (byte < 36) {
59
+ // `0-9a-z`
24
60
  id += byte.toString(36)
25
61
  } else if (byte < 62) {
62
+ // `A-Z`
26
63
  id += (byte - 26).toString(36).toUpperCase()
27
64
  } else if (byte > 62) {
28
65
  id += '-'
@@ -31,4 +68,5 @@ let nanoid = (size = 21) =>
31
68
  }
32
69
  return id
33
70
  }, '')
71
+
34
72
  export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
package/index.cjs CHANGED
@@ -1,7 +1,15 @@
1
1
  let crypto = require('crypto')
2
+
2
3
  let { urlAlphabet } = require('./url-alphabet/index.cjs')
4
+
5
+ // It is best to make fewer, larger requests to the crypto module to
6
+ // avoid system call overhead. So, random numbers are generated in a
7
+ // pool. The pool is a Buffer that is larger than the initial random
8
+ // request size by this multiplier. The pool is enlarged if subsequent
9
+ // requests exceed the maximum buffer size.
3
10
  const POOL_SIZE_MULTIPLIER = 128
4
11
  let pool, poolOffset
12
+
5
13
  let fillPool = bytes => {
6
14
  if (!pool || pool.length < bytes) {
7
15
  pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
@@ -13,33 +21,65 @@ let fillPool = bytes => {
13
21
  }
14
22
  poolOffset += bytes
15
23
  }
24
+
16
25
  let random = bytes => {
17
- fillPool((bytes -= 0))
26
+ // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
27
+ fillPool((bytes |= 0))
18
28
  return pool.subarray(poolOffset - bytes, poolOffset)
19
29
  }
30
+
20
31
  let customRandom = (alphabet, defaultSize, getRandom) => {
32
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
33
+ // values closer to the alphabet size. The bitmask calculates the closest
34
+ // `2^31 - 1` number, which exceeds the alphabet size.
35
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
21
36
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
37
+ // Though, the bitmask solution is not perfect since the bytes exceeding
38
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
39
+ // the random bytes redundancy has to be satisfied.
40
+
41
+ // Note: every hardware random generator call is performance expensive,
42
+ // because the system call for entropy collection takes a lot of time.
43
+ // So, to avoid additional system calls, extra bytes are requested in advance.
44
+
45
+ // Next, a step determines how many random bytes to generate.
46
+ // The number of random bytes gets decided upon the ID size, mask,
47
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
48
+ // according to benchmarks).
22
49
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
50
+
23
51
  return (size = defaultSize) => {
24
52
  let id = ''
25
53
  while (true) {
26
54
  let bytes = getRandom(step)
55
+ // A compact alternative for `for (let i = 0; i < step; i++)`.
27
56
  let i = step
28
57
  while (i--) {
58
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
29
59
  id += alphabet[bytes[i] & mask] || ''
30
60
  if (id.length === size) return id
31
61
  }
32
62
  }
33
63
  }
34
64
  }
65
+
35
66
  let customAlphabet = (alphabet, size = 21) =>
36
67
  customRandom(alphabet, size, random)
68
+
37
69
  let nanoid = (size = 21) => {
38
- fillPool((size -= 0))
70
+ // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
71
+ fillPool((size |= 0))
39
72
  let id = ''
73
+ // We are reading directly from the random pool to avoid creating new array
40
74
  for (let i = poolOffset - size; i < poolOffset; i++) {
75
+ // It is incorrect to use bytes exceeding the alphabet size.
76
+ // The following mask reduces the random byte in the 0-255 value
77
+ // range to the 0-63 value range. Therefore, adding hacks, such
78
+ // as empty string fallback or magic numbers, is unneccessary because
79
+ // the bitmask trims bytes down to the alphabet size.
41
80
  id += urlAlphabet[pool[i] & 63]
42
81
  }
43
82
  return id
44
83
  }
84
+
45
85
  module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
package/index.js CHANGED
@@ -1,7 +1,15 @@
1
1
  import crypto from 'crypto'
2
+
2
3
  import { urlAlphabet } from './url-alphabet/index.js'
4
+
5
+ // It is best to make fewer, larger requests to the crypto module to
6
+ // avoid system call overhead. So, random numbers are generated in a
7
+ // pool. The pool is a Buffer that is larger than the initial random
8
+ // request size by this multiplier. The pool is enlarged if subsequent
9
+ // requests exceed the maximum buffer size.
3
10
  const POOL_SIZE_MULTIPLIER = 128
4
11
  let pool, poolOffset
12
+
5
13
  let fillPool = bytes => {
6
14
  if (!pool || pool.length < bytes) {
7
15
  pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
@@ -13,33 +21,65 @@ let fillPool = bytes => {
13
21
  }
14
22
  poolOffset += bytes
15
23
  }
24
+
16
25
  let random = bytes => {
17
- fillPool((bytes -= 0))
26
+ // `|=` convert `bytes` to number to prevent `valueOf` abusing and pool pollution
27
+ fillPool((bytes |= 0))
18
28
  return pool.subarray(poolOffset - bytes, poolOffset)
19
29
  }
30
+
20
31
  let customRandom = (alphabet, defaultSize, getRandom) => {
32
+ // First, a bitmask is necessary to generate the ID. The bitmask makes bytes
33
+ // values closer to the alphabet size. The bitmask calculates the closest
34
+ // `2^31 - 1` number, which exceeds the alphabet size.
35
+ // For example, the bitmask for the alphabet size 30 is 31 (00011111).
21
36
  let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
37
+ // Though, the bitmask solution is not perfect since the bytes exceeding
38
+ // the alphabet size are refused. Therefore, to reliably generate the ID,
39
+ // the random bytes redundancy has to be satisfied.
40
+
41
+ // Note: every hardware random generator call is performance expensive,
42
+ // because the system call for entropy collection takes a lot of time.
43
+ // So, to avoid additional system calls, extra bytes are requested in advance.
44
+
45
+ // Next, a step determines how many random bytes to generate.
46
+ // The number of random bytes gets decided upon the ID size, mask,
47
+ // alphabet size, and magic number 1.6 (using 1.6 peaks at performance
48
+ // according to benchmarks).
22
49
  let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
50
+
23
51
  return (size = defaultSize) => {
24
52
  let id = ''
25
53
  while (true) {
26
54
  let bytes = getRandom(step)
55
+ // A compact alternative for `for (let i = 0; i < step; i++)`.
27
56
  let i = step
28
57
  while (i--) {
58
+ // Adding `|| ''` refuses a random byte that exceeds the alphabet size.
29
59
  id += alphabet[bytes[i] & mask] || ''
30
60
  if (id.length === size) return id
31
61
  }
32
62
  }
33
63
  }
34
64
  }
65
+
35
66
  let customAlphabet = (alphabet, size = 21) =>
36
67
  customRandom(alphabet, size, random)
68
+
37
69
  let nanoid = (size = 21) => {
38
- fillPool((size -= 0))
70
+ // `|=` convert `size` to number to prevent `valueOf` abusing and pool pollution
71
+ fillPool((size |= 0))
39
72
  let id = ''
73
+ // We are reading directly from the random pool to avoid creating new array
40
74
  for (let i = poolOffset - size; i < poolOffset; i++) {
75
+ // It is incorrect to use bytes exceeding the alphabet size.
76
+ // The following mask reduces the random byte in the 0-255 value
77
+ // range to the 0-63 value range. Therefore, adding hacks, such
78
+ // as empty string fallback or magic numbers, is unneccessary because
79
+ // the bitmask trims bytes down to the alphabet size.
41
80
  id += urlAlphabet[pool[i] & 63]
42
81
  }
43
82
  return id
44
83
  }
84
+
45
85
  export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
@@ -1,21 +1,34 @@
1
+ // This alphabet uses `A-Za-z0-9_-` symbols.
2
+ // The order of characters is optimized for better gzip and brotli compression.
3
+ // References to the same file (works both for gzip and brotli):
4
+ // `'use`, `andom`, and `rict'`
5
+ // References to the brotli default dictionary:
6
+ // `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
1
7
  let urlAlphabet =
2
8
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
9
+
3
10
  let customAlphabet = (alphabet, defaultSize = 21) => {
4
11
  return (size = defaultSize) => {
5
12
  let id = ''
6
- let i = size
13
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
14
+ let i = size | 0
7
15
  while (i--) {
16
+ // `| 0` is more compact and faster than `Math.floor()`.
8
17
  id += alphabet[(Math.random() * alphabet.length) | 0]
9
18
  }
10
19
  return id
11
20
  }
12
21
  }
22
+
13
23
  let nanoid = (size = 21) => {
14
24
  let id = ''
15
- let i = size
25
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
26
+ let i = size | 0
16
27
  while (i--) {
28
+ // `| 0` is more compact and faster than `Math.floor()`.
17
29
  id += urlAlphabet[(Math.random() * 64) | 0]
18
30
  }
19
31
  return id
20
32
  }
33
+
21
34
  module.exports = { nanoid, customAlphabet }
@@ -1,21 +1,34 @@
1
+ // This alphabet uses `A-Za-z0-9_-` symbols.
2
+ // The order of characters is optimized for better gzip and brotli compression.
3
+ // References to the same file (works both for gzip and brotli):
4
+ // `'use`, `andom`, and `rict'`
5
+ // References to the brotli default dictionary:
6
+ // `-26T`, `1983`, `40px`, `75px`, `bush`, `jack`, `mind`, `very`, and `wolf`
1
7
  let urlAlphabet =
2
8
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
9
+
3
10
  let customAlphabet = (alphabet, defaultSize = 21) => {
4
11
  return (size = defaultSize) => {
5
12
  let id = ''
6
- let i = size
13
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
14
+ let i = size | 0
7
15
  while (i--) {
16
+ // `| 0` is more compact and faster than `Math.floor()`.
8
17
  id += alphabet[(Math.random() * alphabet.length) | 0]
9
18
  }
10
19
  return id
11
20
  }
12
21
  }
22
+
13
23
  let nanoid = (size = 21) => {
14
24
  let id = ''
15
- let i = size
25
+ // A compact alternative for `for (var i = 0; i < step; i++)`.
26
+ let i = size | 0
16
27
  while (i--) {
28
+ // `| 0` is more compact and faster than `Math.floor()`.
17
29
  id += urlAlphabet[(Math.random() * 64) | 0]
18
30
  }
19
31
  return id
20
32
  }
33
+
21
34
  export { nanoid, customAlphabet }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nanoid",
3
- "version": "3.3.7",
3
+ "version": "3.3.9",
4
4
  "description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
5
5
  "keywords": [
6
6
  "uuid",
@@ -1,3 +1,7 @@
1
+ // This alphabet uses `A-Za-z0-9_-` symbols.
2
+ // The order of characters is optimized for better gzip and brotli compression.
3
+ // Same as in non-secure/index.js
1
4
  let urlAlphabet =
2
5
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
6
+
3
7
  module.exports = { urlAlphabet }
@@ -1,3 +1,7 @@
1
+ // This alphabet uses `A-Za-z0-9_-` symbols.
2
+ // The order of characters is optimized for better gzip and brotli compression.
3
+ // Same as in non-secure/index.js
1
4
  let urlAlphabet =
2
5
  'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
6
+
3
7
  export { urlAlphabet }