forked from daren.hsu/line_push
update
This commit is contained in:
+9
-453
@@ -3,20 +3,21 @@
|
||||
<img src="https://ai.github.io/nanoid/logo.svg" align="right"
|
||||
alt="Nano ID logo by Anton Lovchikov" width="180" height="94">
|
||||
|
||||
**English** | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md)
|
||||
|
||||
A tiny, secure, URL-friendly, unique string ID generator for JavaScript.
|
||||
|
||||
> “An amazing level of senseless perfectionism,
|
||||
> which is simply impossible not to respect.”
|
||||
|
||||
* **Small.** 108 bytes (minified and gzipped). No dependencies.
|
||||
* **Small.** 130 bytes (minified and gzipped). No dependencies.
|
||||
[Size Limit] controls the size.
|
||||
* **Fast.** It is 40% faster than UUID.
|
||||
* **Safe.** It uses cryptographically strong random APIs.
|
||||
Can be used in clusters.
|
||||
* **Compact.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).
|
||||
* **Fast.** It is 2 times faster than UUID.
|
||||
* **Safe.** It uses hardware random generator. Can be used in clusters.
|
||||
* **Short IDs.** It uses a larger alphabet than UUID (`A-Za-z0-9_-`).
|
||||
So ID size was reduced from 36 to 21 symbols.
|
||||
* **Portable.** Nano ID was ported
|
||||
to [14 programming languages](#other-programming-languages).
|
||||
to [20 programming languages](#other-programming-languages).
|
||||
|
||||
```js
|
||||
import { nanoid } from 'nanoid'
|
||||
@@ -34,450 +35,5 @@ Supports modern browsers, IE [with Babel], Node.js and React Native.
|
||||
alt="Sponsored by Evil Martians" width="236" height="54">
|
||||
</a>
|
||||
|
||||
## Table of Contents
|
||||
|
||||
* [Comparison with UUID](#comparison-with-uuid)
|
||||
* [Benchmark](#benchmark)
|
||||
* [Tools](#tools)
|
||||
* [Security](#security)
|
||||
* [Usage](#usage)
|
||||
* [JS](#js)
|
||||
* [IE](#ie)
|
||||
* [React](#react)
|
||||
* [Create React App](#create-react-app)
|
||||
* [React Native](#react-native)
|
||||
* [Expo](#expo)
|
||||
* [PouchDB and CouchDB](#pouchdb-and-couchdb)
|
||||
* [Mongoose](#mongoose)
|
||||
* [ES Modules](#es-modules)
|
||||
* [Web Workers](#web-workers)
|
||||
* [CLI](#cli)
|
||||
* [Other Programming Languages](#other-programming-languages)
|
||||
* [API](#api)
|
||||
* [Async](#async)
|
||||
* [Non-Secure](#non-secure)
|
||||
* [Custom Alphabet or Size](#custom-alphabet-or-size)
|
||||
* [Custom Random Bytes Generator](#custom-random-bytes-generator)
|
||||
|
||||
|
||||
## Comparison with UUID
|
||||
|
||||
Nano ID is quite comparable to UUID v4 (random-based).
|
||||
It has a similar number of random bits in the ID
|
||||
(126 in Nano ID and 122 in UUID), so it has a similar collision probability:
|
||||
|
||||
> For there to be a one in a billion chance of duplication,
|
||||
> 103 trillion version 4 IDs must be generated.
|
||||
|
||||
There are three main differences between Nano ID and UUID v4:
|
||||
|
||||
1. Nano ID uses a bigger alphabet, so a similar number of random bits
|
||||
are packed in just 21 symbols instead of 36.
|
||||
2. Nano ID code is 3 times less than `uuid/v4` package:
|
||||
108 bytes instead of 345.
|
||||
3. Because of memory allocation tricks, Nano ID is 16% faster than UUID.
|
||||
|
||||
|
||||
## Benchmark
|
||||
|
||||
```rust
|
||||
$ ./test/benchmark
|
||||
nanoid 655,798 ops/sec
|
||||
customAlphabet 635,421 ops/sec
|
||||
uid.sync 375,816 ops/sec
|
||||
uuid v4 396,756 ops/sec
|
||||
secure-random-string 366,434 ops/sec
|
||||
cuid 183,998 ops/sec
|
||||
shortid 59,343 ops/sec
|
||||
|
||||
Async:
|
||||
async nanoid 101,966 ops/sec
|
||||
async customAlphabet 102,471 ops/sec
|
||||
async secure-random-string 97,206 ops/sec
|
||||
uid 91,291 ops/sec
|
||||
|
||||
Non-secure:
|
||||
non-secure nanoid 2,754,423 ops/sec
|
||||
rndm 2,437,262 ops/sec
|
||||
```
|
||||
|
||||
Test configuration: Dell XPS 2-in-a 7390, Fedora 32, Node.js 13.11.
|
||||
|
||||
|
||||
## Tools
|
||||
|
||||
* [ID size calculator] shows collision probability when adjusting
|
||||
the ID alphabet or size.
|
||||
* [`nanoid-dictionary`] with popular alphabets to use with `customAlphabet`.
|
||||
* [`nanoid-good`] to be sure that your ID doesn’t contain any obscene words.
|
||||
|
||||
[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary
|
||||
[ID size calculator]: https://zelark.github.io/nano-id-cc/
|
||||
[`nanoid-good`]: https://github.com/y-gagar1n/nanoid-good
|
||||
|
||||
|
||||
## Security
|
||||
|
||||
*See a good article about random generators theory:
|
||||
[Secure random values (in Node.js)]*
|
||||
|
||||
* **Unpredictability.** Instead of using the unsafe `Math.random()`, Nano ID
|
||||
uses the `crypto` module in Node.js and the Web Crypto API in browsers.
|
||||
These modules use unpredictable hardware random generator.
|
||||
* **Uniformity.** `random % alphabet` is a popular mistake to make when coding
|
||||
an ID generator. The distribution will not be even; there will be a lower
|
||||
chance for some symbols to appear compared to others. So, it will reduce
|
||||
the number of tries when brute-forcing. Nano ID uses a [better algorithm]
|
||||
and is tested for uniformity.
|
||||
|
||||
<img src="img/distribution.png" alt="Nano ID uniformity"
|
||||
width="340" height="135">
|
||||
|
||||
* **Vulnerabilities:** to report a security vulnerability, please use
|
||||
the [Tidelift security contact](https://tidelift.com/security).
|
||||
Tidelift will coordinate the fix and disclosure.
|
||||
|
||||
[Secure random values (in Node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba
|
||||
[better algorithm]: https://github.com/ai/nanoid/blob/master/format.js
|
||||
|
||||
|
||||
## Usage
|
||||
|
||||
### JS
|
||||
|
||||
The main module uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID
|
||||
with 21 characters (to have a collision probability similar to UUID v4).
|
||||
|
||||
```js
|
||||
import { nanoid } from 'nanoid'
|
||||
model.id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
|
||||
```
|
||||
|
||||
If you want to reduce the ID size (and increase collisions probability),
|
||||
you can pass the size as an argument.
|
||||
|
||||
```js
|
||||
nanoid(10) //=> "IRFa-VaY2b"
|
||||
```
|
||||
|
||||
Don’t forget to check the safety of your ID size
|
||||
in our [ID collision probability] calculator.
|
||||
|
||||
You can also use a [custom alphabet](#custom-alphabet-or-size)
|
||||
or a [random generator](#custom-random-bytes-generator).
|
||||
|
||||
[ID collision probability]: https://zelark.github.io/nano-id-cc/
|
||||
|
||||
|
||||
### IE
|
||||
|
||||
If you support IE, you need to [transpile `node_modules`] by Babel
|
||||
and add `crypto` alias:
|
||||
|
||||
```js
|
||||
if (!window.crypto) {
|
||||
window.crypto = window.msCrypto
|
||||
}
|
||||
|
||||
import { nanoid } from 'nanoid'
|
||||
```
|
||||
|
||||
[transpile `node_modules`]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/
|
||||
|
||||
|
||||
### React
|
||||
|
||||
**Do not** call `nanoid` in the `key` prop. In React, `key` should be consistent
|
||||
among renders.
|
||||
|
||||
This is the bad example:
|
||||
|
||||
```jsx
|
||||
<Item key={nanoid()} /> /* DON’T DO IT */
|
||||
```
|
||||
|
||||
This is the good example (`id` will be generated only once):
|
||||
|
||||
```jsx
|
||||
const Element = () => {
|
||||
const [id] = React.useState(nanoid)
|
||||
return <Item key={id} />
|
||||
}
|
||||
```
|
||||
|
||||
If you want to use Nano ID in the `id` prop, you must set some string prefix
|
||||
(it is invalid for the HTML ID to start with a number).
|
||||
|
||||
```jsx
|
||||
<input id={'id' + this.id} type="text"/>
|
||||
```
|
||||
|
||||
|
||||
### Create React App
|
||||
|
||||
Create React App has [a problem](https://github.com/ai/nanoid/issues/205)
|
||||
with ES modules packages.
|
||||
|
||||
```
|
||||
TypeError: (0 , _nanoid.nanoid) is not a function
|
||||
```
|
||||
|
||||
If you have an error above, here is temporary fix:
|
||||
|
||||
1. Use Nano ID 2 instead of 3: `npm i nanoid@^2.0.0`.
|
||||
2. Vote for
|
||||
[pull request](https://github.com/facebook/create-react-app/pull/8768),
|
||||
that fix dual packages support.
|
||||
|
||||
|
||||
### React Native
|
||||
|
||||
React Native does not have built-in random generator.
|
||||
|
||||
1. Check [`react-native-get-random-values`] docs and install it.
|
||||
2. Import it before Nano ID.
|
||||
|
||||
```js
|
||||
import 'react-native-get-random-values'
|
||||
import { nanoid } from 'nanoid'
|
||||
```
|
||||
|
||||
For Expo framework see the next section.
|
||||
|
||||
[`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values
|
||||
|
||||
|
||||
### Expo
|
||||
|
||||
If you use Expo in React Native, you need a different workaround.
|
||||
|
||||
1. Install [`expo-random`](https://www.npmjs.com/package/expo-random).
|
||||
2. Use `nanoid/async` instead of `nanoid`.
|
||||
3. Import `index.native.js` file directly.
|
||||
|
||||
```js
|
||||
import { nanoid } from 'nanoid/async/index.native'
|
||||
|
||||
async function createUser () {
|
||||
user.id = await nanoid()
|
||||
}
|
||||
```
|
||||
|
||||
[`expo-random`]: https://www.npmjs.com/package/expo-random
|
||||
|
||||
|
||||
### PouchDB and CouchDB
|
||||
|
||||
In PouchDB and CouchDB, IDs can’t start with an underscore `_`.
|
||||
A prefix is required to prevent this issue, as Nano ID might use a `_`
|
||||
at the start of the ID by default.
|
||||
|
||||
Override the default ID with the following option:
|
||||
|
||||
```js
|
||||
db.put({
|
||||
_id: 'id' + nanoid(),
|
||||
…
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### Mongoose
|
||||
|
||||
```js
|
||||
const mySchema = new Schema({
|
||||
_id: {
|
||||
type: String,
|
||||
default: () => nanoid()
|
||||
}
|
||||
})
|
||||
```
|
||||
|
||||
|
||||
### ES Modules
|
||||
|
||||
Nano ID provides ES modules. You do not need to do anything to use Nano ID
|
||||
as ESM in webpack, Rollup, Parcel, or Node.js.
|
||||
|
||||
```js
|
||||
import { nanoid } from 'nanoid'
|
||||
```
|
||||
|
||||
For quick hacks, you can load Nano ID from CDN. Special minified
|
||||
`nanoid.js` module is available on jsDelivr.
|
||||
|
||||
Though, it is not recommended to be used in production
|
||||
because of the lower loading performance.
|
||||
|
||||
```js
|
||||
import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js'
|
||||
```
|
||||
|
||||
|
||||
### Web Workers
|
||||
|
||||
Web Workers do not have access to a secure random generator.
|
||||
|
||||
Security is important in IDs when IDs should be unpredictable.
|
||||
For instance, in "access by URL" link generation.
|
||||
If you do not need unpredictable IDs, but you need to use Web Workers,
|
||||
you can use the non‑secure ID generator.
|
||||
|
||||
```js
|
||||
import { nanoid } from 'nanoid/non-secure'
|
||||
nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
|
||||
```
|
||||
|
||||
Note: non-secure IDs are more prone to collision attacks.
|
||||
|
||||
|
||||
### CLI
|
||||
|
||||
You can get unique ID in terminal by calling `npx nanoid`. You need only
|
||||
Node.js in the system. You do not need Nano ID to be installed anywhere.
|
||||
|
||||
```sh
|
||||
$ npx nanoid
|
||||
npx: installed 1 in 0.63s
|
||||
LZfXLFzPPR4NNrgjlWDxn
|
||||
```
|
||||
|
||||
If you want to change alphabet or ID size, you should use [`nanoid-cli`].
|
||||
|
||||
[`nanoid-cli`]: https://github.com/twhitbeck/nanoid-cli
|
||||
|
||||
|
||||
### Other Programming Languages
|
||||
|
||||
Nano ID was ported to many languages. You can use these ports to have
|
||||
the same ID generator on the client and server side.
|
||||
|
||||
* [C#](https://github.com/codeyu/nanoid-net)
|
||||
* [Clojure and ClojureScript](https://github.com/zelark/nano-id)
|
||||
* [Crystal](https://github.com/mamantoha/nanoid.cr)
|
||||
* [Dart](https://github.com/pd4d10/nanoid-dart)
|
||||
* [Deno](https://github.com/ianfabs/nanoid)
|
||||
* [Go](https://github.com/matoous/go-nanoid)
|
||||
* [Elixir](https://github.com/railsmechanic/nanoid)
|
||||
* [Haskell](https://github.com/4e6/nanoid-hs)
|
||||
* [Janet](https://sr.ht/~statianzo/janet-nanoid/)
|
||||
* [Java](https://github.com/aventrix/jnanoid)
|
||||
* [Nim](https://github.com/icyphox/nanoid.nim)
|
||||
* [PHP](https://github.com/hidehalo/nanoid-php)
|
||||
* [Python](https://github.com/puyuan/py-nanoid)
|
||||
with [dictionaries](https://pypi.org/project/nanoid-dictionary)
|
||||
* [Ruby](https://github.com/radeno/nanoid.rb)
|
||||
* [Rust](https://github.com/nikolay-govorov/nanoid)
|
||||
* [Swift](https://github.com/antiflasher/NanoID)
|
||||
|
||||
Also, [CLI] is available to generate IDs from a command line.
|
||||
|
||||
[CLI]: #cli
|
||||
|
||||
|
||||
## API
|
||||
|
||||
### Async
|
||||
|
||||
To generate hardware random bytes, CPU collects electromagnetic noise.
|
||||
In the synchronous API during the noise collection, the CPU is busy and
|
||||
cannot do anything useful in parallel.
|
||||
|
||||
Using the asynchronous API of Nano ID, another code can run during
|
||||
the entropy collection.
|
||||
|
||||
```js
|
||||
import { nanoid } from 'nanoid/async'
|
||||
|
||||
async function createUser () {
|
||||
user.id = await nanoid()
|
||||
}
|
||||
```
|
||||
|
||||
Unfortunately, you will lose Web Crypto API advantages in a browser
|
||||
if you the asynchronous API. So, currently, in the browser, you are limited
|
||||
with either security or asynchronous behavior.
|
||||
|
||||
|
||||
### Non-Secure
|
||||
|
||||
By default, Nano ID uses hardware random bytes generation for security
|
||||
and low collision probability. If you are not so concerned with security
|
||||
and more concerned with performance, you can use the faster non-secure generator.
|
||||
|
||||
```js
|
||||
import { nanoid } from 'nanoid/non-secure'
|
||||
const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ"
|
||||
```
|
||||
|
||||
Note: your IDs will be more predictable and prone to collision attacks.
|
||||
|
||||
|
||||
### Custom Alphabet or Size
|
||||
|
||||
`customAlphabet` allows you to create `nanoid` with your own alphabet
|
||||
and ID size.
|
||||
|
||||
```js
|
||||
import { customAlphabet } from 'nanoid'
|
||||
const nanoid = customAlphabet('1234567890abcdef', 10)
|
||||
model.id = nanoid() //=> "4f90d13a42"
|
||||
```
|
||||
|
||||
Check the safety of your custom alphabet and ID size in our
|
||||
[ID collision probability] calculator. For more alphabets, check out the options
|
||||
in [`nanoid-dictionary`].
|
||||
|
||||
Alphabet must contain 256 symbols or less.
|
||||
Otherwise, the security of the internal generator algorithm is not guaranteed.
|
||||
|
||||
Customizable asynchronous and non-secure APIs are also available:
|
||||
|
||||
```js
|
||||
import { customAlphabet } from 'nanoid/async'
|
||||
const nanoid = customAlphabet('1234567890abcdef', 10)
|
||||
async function createUser () {
|
||||
user.id = await nanoid()
|
||||
}
|
||||
```
|
||||
|
||||
```js
|
||||
import { customAlphabet } from 'nanoid/non-secure'
|
||||
const nanoid = customAlphabet('1234567890abcdef', 10)
|
||||
user.id = nanoid()
|
||||
```
|
||||
|
||||
[ID collision probability]: https://alex7kom.github.io/nano-nanoid-cc/
|
||||
[`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary
|
||||
|
||||
|
||||
### Custom Random Bytes Generator
|
||||
|
||||
`customRandom` allows you to create a `nanoid` and replace alphabet
|
||||
and the default random bytes generator.
|
||||
|
||||
In this example, a seed-based generator is used:
|
||||
|
||||
```js
|
||||
import { customRandom } from 'nanoid'
|
||||
|
||||
const rng = seedrandom(seed)
|
||||
const nanoid = customRandom('abcdef', 10, size => {
|
||||
return (new Uint8Array(size)).map(() => 256 * rng())
|
||||
})
|
||||
|
||||
nanoid() //=> "fbaefaadeb"
|
||||
```
|
||||
|
||||
`random` callback must accept the array size and return an array
|
||||
with random numbers.
|
||||
|
||||
If you want to use the same URL-friendly symbols with `customRandom`,
|
||||
you can get the default alphabet using the `urlAlphabet`.
|
||||
|
||||
```js
|
||||
const { customRandom, urlAlphabet } = require('nanoid')
|
||||
const nanoid = customRandom(urlAlphabet, 10, random)
|
||||
```
|
||||
|
||||
Asynchronous and non-secure APIs are not available for `customRandom`.
|
||||
## Docs
|
||||
Read **[full docs](https://github.com/ai/nanoid#readme)** on GitHub.
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
|
||||
let step = -~((1.6 * mask * defaultSize) / alphabet.length)
|
||||
return async (size = defaultSize) => {
|
||||
let id = ''
|
||||
while (true) {
|
||||
let bytes = crypto.getRandomValues(new Uint8Array(step))
|
||||
let i = step
|
||||
while (i--) {
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
if (id.length === size) return id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let nanoid = async (size = 21) => {
|
||||
let id = ''
|
||||
let bytes = crypto.getRandomValues(new Uint8Array(size))
|
||||
while (size--) {
|
||||
let byte = bytes[size] & 63
|
||||
if (byte < 36) {
|
||||
id += byte.toString(36)
|
||||
} else if (byte < 62) {
|
||||
id += (byte - 26).toString(36).toUpperCase()
|
||||
} else if (byte < 63) {
|
||||
id += '_'
|
||||
} else {
|
||||
id += '-'
|
||||
}
|
||||
}
|
||||
return id
|
||||
}
|
||||
module.exports = { nanoid, customAlphabet, random }
|
||||
+7
-44
@@ -1,63 +1,27 @@
|
||||
let random = bytes =>
|
||||
Promise.resolve(crypto.getRandomValues(new Uint8Array(bytes)))
|
||||
|
||||
let customAlphabet = (alphabet, size) => {
|
||||
// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
|
||||
// values closer to the alphabet size. The bitmask calculates the closest
|
||||
// `2^31 - 1` number, which exceeds the alphabet size.
|
||||
// For example, the bitmask for the alphabet size 30 is 31 (00011111).
|
||||
// `Math.clz32` is not used, because it is not available in browsers.
|
||||
let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes))
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
|
||||
// Though, the bitmask solution is not perfect since the bytes exceeding
|
||||
// the alphabet size are refused. Therefore, to reliably generate the ID,
|
||||
// the random bytes redundancy has to be satisfied.
|
||||
|
||||
// Note: every hardware random generator call is performance expensive,
|
||||
// because the system call for entropy collection takes a lot of time.
|
||||
// So, to avoid additional system calls, extra bytes are requested in advance.
|
||||
|
||||
// Next, a step determines how many random bytes to generate.
|
||||
// The number of random bytes gets decided upon the ID size, mask,
|
||||
// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
|
||||
// according to benchmarks).
|
||||
|
||||
// `-~f => Math.ceil(f)` if f is a float
|
||||
// `-~i => i + 1` if i is an integer
|
||||
let step = -~((1.6 * mask * size) / alphabet.length)
|
||||
|
||||
return () => {
|
||||
let step = -~((1.6 * mask * defaultSize) / alphabet.length)
|
||||
return async (size = defaultSize) => {
|
||||
let id = ''
|
||||
while (true) {
|
||||
let bytes = crypto.getRandomValues(new Uint8Array(step))
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = step
|
||||
while (i--) {
|
||||
// Adding `|| ''` refuses a random byte that exceeds the alphabet size.
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
// `id.length + 1 === size` is a more compact option.
|
||||
if (id.length === +size) return id
|
||||
if (id.length === size) return id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let nanoid = (size = 21) => {
|
||||
let nanoid = async (size = 21) => {
|
||||
let id = ''
|
||||
let bytes = crypto.getRandomValues(new Uint8Array(size))
|
||||
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
while (size--) {
|
||||
// It is incorrect to use bytes exceeding the alphabet size.
|
||||
// The following mask reduces the random byte in the 0-255 value
|
||||
// range to the 0-63 value range. Therefore, adding hacks, such
|
||||
// as empty string fallback or magic numbers, is unneccessary because
|
||||
// the bitmask trims bytes down to the alphabet size.
|
||||
let byte = bytes[size] & 63
|
||||
if (byte < 36) {
|
||||
// `0-9a-z`
|
||||
id += byte.toString(36)
|
||||
} else if (byte < 62) {
|
||||
// `A-Z`
|
||||
id += (byte - 26).toString(36).toUpperCase()
|
||||
} else if (byte < 63) {
|
||||
id += '_'
|
||||
@@ -65,7 +29,6 @@ let nanoid = (size = 21) => {
|
||||
id += '-'
|
||||
}
|
||||
}
|
||||
return Promise.resolve(id)
|
||||
return id
|
||||
}
|
||||
|
||||
export { nanoid, customAlphabet, random }
|
||||
|
||||
+6
-43
@@ -1,14 +1,7 @@
|
||||
let crypto = require('crypto')
|
||||
|
||||
let { urlAlphabet } = require('../url-alphabet/index.cjs')
|
||||
|
||||
// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
|
||||
// because it is possible to use in combination with `Buffer.allocUnsafe()`.
|
||||
let random = bytes =>
|
||||
new Promise((resolve, reject) => {
|
||||
// `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
|
||||
// Memory flushing is unnecessary since the buffer allocation itself resets
|
||||
// the memory with the new bytes.
|
||||
crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
@@ -17,56 +10,26 @@ let random = bytes =>
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
let customAlphabet = (alphabet, size) => {
|
||||
// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
|
||||
// values closer to the alphabet size. The bitmask calculates the closest
|
||||
// `2^31 - 1` number, which exceeds the alphabet size.
|
||||
// For example, the bitmask for the alphabet size 30 is 31 (00011111).
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
||||
// Though, the bitmask solution is not perfect since the bytes exceeding
|
||||
// the alphabet size are refused. Therefore, to reliably generate the ID,
|
||||
// the random bytes redundancy has to be satisfied.
|
||||
|
||||
// Note: every hardware random generator call is performance expensive,
|
||||
// because the system call for entropy collection takes a lot of time.
|
||||
// So, to avoid additional system calls, extra bytes are requested in advance.
|
||||
|
||||
// Next, a step determines how many random bytes to generate.
|
||||
// The number of random bytes gets decided upon the ID size, mask,
|
||||
// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
|
||||
// according to benchmarks).
|
||||
let step = Math.ceil((1.6 * mask * size) / alphabet.length)
|
||||
|
||||
let tick = id =>
|
||||
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
|
||||
let tick = (id, size = defaultSize) =>
|
||||
random(step).then(bytes => {
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = step
|
||||
while (i--) {
|
||||
// Adding `|| ''` refuses a random byte that exceeds the alphabet size.
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
// `id.length + 1 === size` is a more compact option.
|
||||
if (id.length === +size) return id
|
||||
if (id.length === size) return id
|
||||
}
|
||||
return tick(id)
|
||||
return tick(id, size)
|
||||
})
|
||||
|
||||
return () => tick('')
|
||||
return size => tick('', size)
|
||||
}
|
||||
|
||||
let nanoid = (size = 21) =>
|
||||
random(size).then(bytes => {
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
while (size--) {
|
||||
// It is incorrect to use bytes exceeding the alphabet size.
|
||||
// The following mask reduces the random byte in the 0-255 value
|
||||
// range to the 0-63 value range. Therefore, adding hacks, such
|
||||
// as empty string fallback or magic numbers, is unneccessary because
|
||||
// the bitmask trims bytes down to the alphabet size.
|
||||
id += urlAlphabet[bytes[size] & 63]
|
||||
}
|
||||
return id
|
||||
})
|
||||
|
||||
module.exports = { nanoid, customAlphabet, random }
|
||||
|
||||
+7
-7
@@ -14,7 +14,7 @@
|
||||
* @param size Size of the ID. The default size is 21.
|
||||
* @returns A promise with a random string.
|
||||
*/
|
||||
export function nanoid (size?: number): Promise<string>
|
||||
export function nanoid(size?: number): Promise<string>
|
||||
|
||||
/**
|
||||
* A low-level function.
|
||||
@@ -24,8 +24,8 @@ export function nanoid (size?: number): Promise<string>
|
||||
* will not be secure.
|
||||
*
|
||||
* @param alphabet Alphabet used to generate the ID.
|
||||
* @param size Size of the ID.
|
||||
* @returns A promise with a random string.
|
||||
* @param defaultSize Size of the ID. The default size is 21.
|
||||
* @returns A function that returns a promise with a random string.
|
||||
*
|
||||
* ```js
|
||||
* import { customAlphabet } from 'nanoid/async'
|
||||
@@ -35,10 +35,10 @@ export function nanoid (size?: number): Promise<string>
|
||||
* })
|
||||
* ```
|
||||
*/
|
||||
export function customAlphabet (
|
||||
export function customAlphabet(
|
||||
alphabet: string,
|
||||
size: number
|
||||
): () => Promise<string>
|
||||
defaultSize?: number
|
||||
): (size?: number) => Promise<string>
|
||||
|
||||
/**
|
||||
* Generate an array of random bytes collected from hardware noise.
|
||||
@@ -53,4 +53,4 @@ export function customAlphabet (
|
||||
* @param bytes Size of the array.
|
||||
* @returns A promise with a random bytes array.
|
||||
*/
|
||||
export function random (bytes: number): Promise<Uint8Array>
|
||||
export function random(bytes: number): Promise<Uint8Array>
|
||||
|
||||
+6
-43
@@ -1,14 +1,7 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
import { urlAlphabet } from '../url-alphabet/index.js'
|
||||
|
||||
// `crypto.randomFill()` is a little faster than `crypto.randomBytes()`,
|
||||
// because it is possible to use in combination with `Buffer.allocUnsafe()`.
|
||||
let random = bytes =>
|
||||
new Promise((resolve, reject) => {
|
||||
// `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
|
||||
// Memory flushing is unnecessary since the buffer allocation itself resets
|
||||
// the memory with the new bytes.
|
||||
crypto.randomFill(Buffer.allocUnsafe(bytes), (err, buf) => {
|
||||
if (err) {
|
||||
reject(err)
|
||||
@@ -17,56 +10,26 @@ let random = bytes =>
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
let customAlphabet = (alphabet, size) => {
|
||||
// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
|
||||
// values closer to the alphabet size. The bitmask calculates the closest
|
||||
// `2^31 - 1` number, which exceeds the alphabet size.
|
||||
// For example, the bitmask for the alphabet size 30 is 31 (00011111).
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
||||
// Though, the bitmask solution is not perfect since the bytes exceeding
|
||||
// the alphabet size are refused. Therefore, to reliably generate the ID,
|
||||
// the random bytes redundancy has to be satisfied.
|
||||
|
||||
// Note: every hardware random generator call is performance expensive,
|
||||
// because the system call for entropy collection takes a lot of time.
|
||||
// So, to avoid additional system calls, extra bytes are requested in advance.
|
||||
|
||||
// Next, a step determines how many random bytes to generate.
|
||||
// The number of random bytes gets decided upon the ID size, mask,
|
||||
// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
|
||||
// according to benchmarks).
|
||||
let step = Math.ceil((1.6 * mask * size) / alphabet.length)
|
||||
|
||||
let tick = id =>
|
||||
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
|
||||
let tick = (id, size = defaultSize) =>
|
||||
random(step).then(bytes => {
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = step
|
||||
while (i--) {
|
||||
// Adding `|| ''` refuses a random byte that exceeds the alphabet size.
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
// `id.length + 1 === size` is a more compact option.
|
||||
if (id.length === +size) return id
|
||||
if (id.length === size) return id
|
||||
}
|
||||
return tick(id)
|
||||
return tick(id, size)
|
||||
})
|
||||
|
||||
return () => tick('')
|
||||
return size => tick('', size)
|
||||
}
|
||||
|
||||
let nanoid = (size = 21) =>
|
||||
random(size).then(bytes => {
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
while (size--) {
|
||||
// It is incorrect to use bytes exceeding the alphabet size.
|
||||
// The following mask reduces the random byte in the 0-255 value
|
||||
// range to the 0-63 value range. Therefore, adding hacks, such
|
||||
// as empty string fallback or magic numbers, is unneccessary because
|
||||
// the bitmask trims bytes down to the alphabet size.
|
||||
id += urlAlphabet[bytes[size] & 63]
|
||||
}
|
||||
return id
|
||||
})
|
||||
|
||||
export { nanoid, customAlphabet, random }
|
||||
|
||||
+6
-38
@@ -1,58 +1,26 @@
|
||||
import { getRandomBytesAsync } from 'expo-random'
|
||||
|
||||
import { urlAlphabet } from '../url-alphabet/index.js'
|
||||
|
||||
let random = getRandomBytesAsync
|
||||
|
||||
let customAlphabet = (alphabet, size) => {
|
||||
// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
|
||||
// values closer to the alphabet size. The bitmask calculates the closest
|
||||
// `2^31 - 1` number, which exceeds the alphabet size.
|
||||
// For example, the bitmask for the alphabet size 30 is 31 (00011111).
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
||||
// Though, the bitmask solution is not perfect since the bytes exceeding
|
||||
// the alphabet size are refused. Therefore, to reliably generate the ID,
|
||||
// the random bytes redundancy has to be satisfied.
|
||||
|
||||
// Note: every hardware random generator call is performance expensive,
|
||||
// because the system call for entropy collection takes a lot of time.
|
||||
// So, to avoid additional system calls, extra bytes are requested in advance.
|
||||
|
||||
// Next, a step determines how many random bytes to generate.
|
||||
// The number of random bytes gets decided upon the ID size, mask,
|
||||
// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
|
||||
// according to benchmarks).
|
||||
let step = Math.ceil((1.6 * mask * size) / alphabet.length)
|
||||
|
||||
let tick = id =>
|
||||
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
|
||||
let tick = (id, size = defaultSize) =>
|
||||
random(step).then(bytes => {
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = step
|
||||
while (i--) {
|
||||
// Adding `|| ''` refuses a random byte that exceeds the alphabet size.
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
// `id.length + 1 === size` is a more compact option.
|
||||
if (id.length === +size) return id
|
||||
if (id.length === size) return id
|
||||
}
|
||||
return tick(id)
|
||||
return tick(id, size)
|
||||
})
|
||||
|
||||
return () => tick('')
|
||||
return size => tick('', size)
|
||||
}
|
||||
|
||||
let nanoid = (size = 21) =>
|
||||
random(size).then(bytes => {
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
while (size--) {
|
||||
// It is incorrect to use bytes exceeding the alphabet size.
|
||||
// The following mask reduces the random byte in the 0-255 value
|
||||
// range to the 0-63 value range. Therefore, adding hacks, such
|
||||
// as empty string fallback or magic numbers, is unneccessary because
|
||||
// the bitmask trims bytes down to the alphabet size.
|
||||
id += urlAlphabet[bytes[size] & 63]
|
||||
}
|
||||
return id
|
||||
})
|
||||
|
||||
export { nanoid, customAlphabet, random }
|
||||
|
||||
+2
-1
@@ -6,6 +6,7 @@
|
||||
"./index.js": "./index.native.js"
|
||||
},
|
||||
"browser": {
|
||||
"./index.js": "./index.browser.js"
|
||||
"./index.js": "./index.browser.js",
|
||||
"./index.cjs": "./index.browser.cjs"
|
||||
}
|
||||
}
|
||||
+52
-2
@@ -1,5 +1,55 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
let { nanoid } = require('..')
|
||||
let { nanoid, customAlphabet } = require('..')
|
||||
|
||||
process.stdout.write(nanoid() + '\n')
|
||||
function print(msg) {
|
||||
process.stdout.write(msg + '\n')
|
||||
}
|
||||
|
||||
function error(msg) {
|
||||
process.stderr.write(msg + '\n')
|
||||
process.exit(1)
|
||||
}
|
||||
|
||||
if (process.argv.includes('--help') || process.argv.includes('-h')) {
|
||||
print(`
|
||||
Usage
|
||||
$ nanoid [options]
|
||||
|
||||
Options
|
||||
-s, --size Generated ID size
|
||||
-a, --alphabet Alphabet to use
|
||||
-h, --help Show this help
|
||||
|
||||
Examples
|
||||
$ nanoid --s 15
|
||||
S9sBF77U6sDB8Yg
|
||||
|
||||
$ nanoid --size 10 --alphabet abc
|
||||
bcabababca`)
|
||||
process.exit()
|
||||
}
|
||||
|
||||
let alphabet, size
|
||||
for (let i = 2; i < process.argv.length; i++) {
|
||||
let arg = process.argv[i]
|
||||
if (arg === '--size' || arg === '-s') {
|
||||
size = Number(process.argv[i + 1])
|
||||
i += 1
|
||||
if (Number.isNaN(size) || size <= 0) {
|
||||
error('Size must be positive integer')
|
||||
}
|
||||
} else if (arg === '--alphabet' || arg === '-a') {
|
||||
alphabet = process.argv[i + 1]
|
||||
i += 1
|
||||
} else {
|
||||
error('Unknown argument ' + arg)
|
||||
}
|
||||
}
|
||||
|
||||
if (alphabet) {
|
||||
let customNanoid = customAlphabet(alphabet, size)
|
||||
print(customNanoid())
|
||||
} else {
|
||||
print(nanoid(size))
|
||||
}
|
||||
|
||||
+34
@@ -0,0 +1,34 @@
|
||||
let { urlAlphabet } = require('./url-alphabet/index.cjs')
|
||||
let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
|
||||
let customRandom = (alphabet, defaultSize, getRandom) => {
|
||||
let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
|
||||
let step = -~((1.6 * mask * defaultSize) / alphabet.length)
|
||||
return (size = defaultSize) => {
|
||||
let id = ''
|
||||
while (true) {
|
||||
let bytes = getRandom(step)
|
||||
let j = step
|
||||
while (j--) {
|
||||
id += alphabet[bytes[j] & mask] || ''
|
||||
if (id.length === size) return id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
let customAlphabet = (alphabet, size = 21) =>
|
||||
customRandom(alphabet, size, random)
|
||||
let nanoid = (size = 21) =>
|
||||
crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
|
||||
byte &= 63
|
||||
if (byte < 36) {
|
||||
id += byte.toString(36)
|
||||
} else if (byte < 62) {
|
||||
id += (byte - 26).toString(36).toUpperCase()
|
||||
} else if (byte > 62) {
|
||||
id += '-'
|
||||
} else {
|
||||
id += '_'
|
||||
}
|
||||
return id
|
||||
}, '')
|
||||
module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
|
||||
+14
-86
@@ -1,106 +1,34 @@
|
||||
// This file replaces `index.js` in bundlers like webpack or Rollup,
|
||||
// according to `browser` config in `package.json`.
|
||||
|
||||
import { urlAlphabet } from './url-alphabet/index.js'
|
||||
|
||||
if (process.env.NODE_ENV !== 'production') {
|
||||
// All bundlers will remove this block in the production bundle.
|
||||
if (
|
||||
typeof navigator !== 'undefined' &&
|
||||
navigator.product === 'ReactNative' &&
|
||||
typeof crypto === 'undefined'
|
||||
) {
|
||||
throw new Error(
|
||||
'React Native does not have a built-in secure random generator. ' +
|
||||
'If you don’t need unpredictable IDs use `nanoid/non-secure`. ' +
|
||||
'For secure IDs, import `react-native-get-random-values` ' +
|
||||
'before Nano ID. If you use Expo, install `expo-random` ' +
|
||||
'and use `nanoid/async`.'
|
||||
)
|
||||
}
|
||||
if (typeof msCrypto !== 'undefined' && typeof crypto === 'undefined') {
|
||||
throw new Error(
|
||||
'Add `if (!window.crypto) window.crypto = window.msCrypto` ' +
|
||||
'before Nano ID to fix IE 11 support'
|
||||
)
|
||||
}
|
||||
if (typeof crypto === 'undefined') {
|
||||
throw new Error(
|
||||
'Your browser does not have secure random generator. ' +
|
||||
'If you don’t need unpredictable IDs, you can use nanoid/non-secure.'
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
let random = bytes => crypto.getRandomValues(new Uint8Array(bytes))
|
||||
|
||||
let customRandom = (alphabet, size, getRandom) => {
|
||||
// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
|
||||
// values closer to the alphabet size. The bitmask calculates the closest
|
||||
// `2^31 - 1` number, which exceeds the alphabet size.
|
||||
// For example, the bitmask for the alphabet size 30 is 31 (00011111).
|
||||
// `Math.clz32` is not used, because it is not available in browsers.
|
||||
let customRandom = (alphabet, defaultSize, getRandom) => {
|
||||
let mask = (2 << (Math.log(alphabet.length - 1) / Math.LN2)) - 1
|
||||
// Though, the bitmask solution is not perfect since the bytes exceeding
|
||||
// the alphabet size are refused. Therefore, to reliably generate the ID,
|
||||
// the random bytes redundancy has to be satisfied.
|
||||
|
||||
// Note: every hardware random generator call is performance expensive,
|
||||
// because the system call for entropy collection takes a lot of time.
|
||||
// So, to avoid additional system calls, extra bytes are requested in advance.
|
||||
|
||||
// Next, a step determines how many random bytes to generate.
|
||||
// The number of random bytes gets decided upon the ID size, mask,
|
||||
// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
|
||||
// according to benchmarks).
|
||||
|
||||
// `-~f => Math.ceil(f)` if f is a float
|
||||
// `-~i => i + 1` if i is an integer
|
||||
let step = -~((1.6 * mask * size) / alphabet.length)
|
||||
|
||||
return () => {
|
||||
let step = -~((1.6 * mask * defaultSize) / alphabet.length)
|
||||
return (size = defaultSize) => {
|
||||
let id = ''
|
||||
while (true) {
|
||||
let bytes = getRandom(step)
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let j = step
|
||||
while (j--) {
|
||||
// Adding `|| ''` refuses a random byte that exceeds the alphabet size.
|
||||
id += alphabet[bytes[j] & mask] || ''
|
||||
// `id.length + 1 === size` is a more compact option.
|
||||
if (id.length === +size) return id
|
||||
if (id.length === size) return id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)
|
||||
|
||||
let nanoid = (size = 21) => {
|
||||
let id = ''
|
||||
let bytes = crypto.getRandomValues(new Uint8Array(size))
|
||||
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
while (size--) {
|
||||
// It is incorrect to use bytes exceeding the alphabet size.
|
||||
// The following mask reduces the random byte in the 0-255 value
|
||||
// range to the 0-63 value range. Therefore, adding hacks, such
|
||||
// as empty string fallback or magic numbers, is unneccessary because
|
||||
// the bitmask trims bytes down to the alphabet size.
|
||||
let byte = bytes[size] & 63
|
||||
let customAlphabet = (alphabet, size = 21) =>
|
||||
customRandom(alphabet, size, random)
|
||||
let nanoid = (size = 21) =>
|
||||
crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => {
|
||||
byte &= 63
|
||||
if (byte < 36) {
|
||||
// `0-9a-z`
|
||||
id += byte.toString(36)
|
||||
} else if (byte < 62) {
|
||||
// `A-Z`
|
||||
id += (byte - 26).toString(36).toUpperCase()
|
||||
} else if (byte < 63) {
|
||||
id += '_'
|
||||
} else {
|
||||
} else if (byte > 62) {
|
||||
id += '-'
|
||||
} else {
|
||||
id += '_'
|
||||
}
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
return id
|
||||
}, '')
|
||||
export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
|
||||
|
||||
+24
-52
@@ -1,73 +1,45 @@
|
||||
let crypto = require('crypto')
|
||||
|
||||
let { urlAlphabet } = require('./url-alphabet/index.cjs')
|
||||
|
||||
// We reuse buffers with the same size to avoid memory fragmentations
|
||||
// for better performance.
|
||||
let buffers = {}
|
||||
let random = bytes => {
|
||||
let buffer = buffers[bytes]
|
||||
if (!buffer) {
|
||||
// `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
|
||||
// Memory flushing is unnecessary since the buffer allocation itself resets
|
||||
// the memory with the new bytes.
|
||||
buffer = Buffer.allocUnsafe(bytes)
|
||||
if (bytes <= 255) buffers[bytes] = buffer
|
||||
const POOL_SIZE_MULTIPLIER = 128
|
||||
let pool, poolOffset
|
||||
let fillPool = bytes => {
|
||||
if (!pool || pool.length < bytes) {
|
||||
pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
|
||||
crypto.randomFillSync(pool)
|
||||
poolOffset = 0
|
||||
} else if (poolOffset + bytes > pool.length) {
|
||||
crypto.randomFillSync(pool)
|
||||
poolOffset = 0
|
||||
}
|
||||
return crypto.randomFillSync(buffer)
|
||||
poolOffset += bytes
|
||||
}
|
||||
|
||||
let customRandom = (alphabet, size, getRandom) => {
|
||||
// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
|
||||
// values closer to the alphabet size. The bitmask calculates the closest
|
||||
// `2^31 - 1` number, which exceeds the alphabet size.
|
||||
// For example, the bitmask for the alphabet size 30 is 31 (00011111).
|
||||
let random = bytes => {
|
||||
fillPool((bytes -= 0))
|
||||
return pool.subarray(poolOffset - bytes, poolOffset)
|
||||
}
|
||||
let customRandom = (alphabet, defaultSize, getRandom) => {
|
||||
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
||||
// Though, the bitmask solution is not perfect since the bytes exceeding
|
||||
// the alphabet size are refused. Therefore, to reliably generate the ID,
|
||||
// the random bytes redundancy has to be satisfied.
|
||||
|
||||
// Note: every hardware random generator call is performance expensive,
|
||||
// because the system call for entropy collection takes a lot of time.
|
||||
// So, to avoid additional system calls, extra bytes are requested in advance.
|
||||
|
||||
// Next, a step determines how many random bytes to generate.
|
||||
// The number of random bytes gets decided upon the ID size, mask,
|
||||
// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
|
||||
// according to benchmarks).
|
||||
let step = Math.ceil((1.6 * mask * size) / alphabet.length)
|
||||
|
||||
return () => {
|
||||
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
|
||||
return (size = defaultSize) => {
|
||||
let id = ''
|
||||
while (true) {
|
||||
let bytes = getRandom(step)
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = step
|
||||
while (i--) {
|
||||
// Adding `|| ''` refuses a random byte that exceeds the alphabet size.
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
// `id.length + 1 === size` is a more compact option.
|
||||
if (id.length === +size) return id
|
||||
if (id.length === size) return id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)
|
||||
|
||||
let customAlphabet = (alphabet, size = 21) =>
|
||||
customRandom(alphabet, size, random)
|
||||
let nanoid = (size = 21) => {
|
||||
let bytes = random(size)
|
||||
fillPool((size -= 0))
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
while (size--) {
|
||||
// It is incorrect to use bytes exceeding the alphabet size.
|
||||
// The following mask reduces the random byte in the 0-255 value
|
||||
// range to the 0-63 value range. Therefore, adding hacks, such
|
||||
// as empty string fallback or magic numbers, is unneccessary because
|
||||
// the bitmask trims bytes down to the alphabet size.
|
||||
id += urlAlphabet[bytes[size] & 63]
|
||||
for (let i = poolOffset - size; i < poolOffset; i++) {
|
||||
id += urlAlphabet[pool[i] & 63]
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random }
|
||||
|
||||
+9
-6
@@ -12,7 +12,7 @@
|
||||
* @param size Size of the ID. The default size is 21.
|
||||
* @returns A random string.
|
||||
*/
|
||||
export function nanoid (size?: number): string
|
||||
export function nanoid(size?: number): string
|
||||
|
||||
/**
|
||||
* Generate secure unique ID with custom alphabet.
|
||||
@@ -21,7 +21,7 @@ export function nanoid (size?: number): string
|
||||
* will not be secure.
|
||||
*
|
||||
* @param alphabet Alphabet used to generate the ID.
|
||||
* @param size Size of the ID.
|
||||
* @param defaultSize Size of the ID. The default size is 21.
|
||||
* @returns A random string generator.
|
||||
*
|
||||
* ```js
|
||||
@@ -30,7 +30,10 @@ export function nanoid (size?: number): string
|
||||
* nanoid() //=> "8ё56а"
|
||||
* ```
|
||||
*/
|
||||
export function customAlphabet (alphabet: string, size: number): () => string
|
||||
export function customAlphabet(
|
||||
alphabet: string,
|
||||
defaultSize?: number
|
||||
): (size?: number) => string
|
||||
|
||||
/**
|
||||
* Generate unique ID with custom random generator and alphabet.
|
||||
@@ -57,7 +60,7 @@ export function customAlphabet (alphabet: string, size: number): () => string
|
||||
* @param random A random bytes generator.
|
||||
* @returns A random string generator.
|
||||
*/
|
||||
export function customRandom (
|
||||
export function customRandom(
|
||||
alphabet: string,
|
||||
size: number,
|
||||
random: (bytes: number) => Uint8Array
|
||||
@@ -68,7 +71,7 @@ export function customRandom (
|
||||
*
|
||||
* ```js
|
||||
* import { urlAlphabet } from 'nanoid'
|
||||
* const nanoid = customRandom(urlAlphabet, 10)
|
||||
* const nanoid = customAlphabet(urlAlphabet, 10)
|
||||
* nanoid() //=> "Uakgb_J5m9"
|
||||
* ```
|
||||
*/
|
||||
@@ -85,4 +88,4 @@ export const urlAlphabet: string
|
||||
* @param bytes Size of the array.
|
||||
* @returns An array of random bytes.
|
||||
*/
|
||||
export function random (bytes: number): Uint8Array
|
||||
export function random(bytes: number): Uint8Array
|
||||
|
||||
+24
-52
@@ -1,73 +1,45 @@
|
||||
import crypto from 'crypto'
|
||||
|
||||
import { urlAlphabet } from './url-alphabet/index.js'
|
||||
|
||||
// We reuse buffers with the same size to avoid memory fragmentations
|
||||
// for better performance.
|
||||
let buffers = {}
|
||||
let random = bytes => {
|
||||
let buffer = buffers[bytes]
|
||||
if (!buffer) {
|
||||
// `Buffer.allocUnsafe()` is faster because it doesn’t flush the memory.
|
||||
// Memory flushing is unnecessary since the buffer allocation itself resets
|
||||
// the memory with the new bytes.
|
||||
buffer = Buffer.allocUnsafe(bytes)
|
||||
if (bytes <= 255) buffers[bytes] = buffer
|
||||
const POOL_SIZE_MULTIPLIER = 128
|
||||
let pool, poolOffset
|
||||
let fillPool = bytes => {
|
||||
if (!pool || pool.length < bytes) {
|
||||
pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)
|
||||
crypto.randomFillSync(pool)
|
||||
poolOffset = 0
|
||||
} else if (poolOffset + bytes > pool.length) {
|
||||
crypto.randomFillSync(pool)
|
||||
poolOffset = 0
|
||||
}
|
||||
return crypto.randomFillSync(buffer)
|
||||
poolOffset += bytes
|
||||
}
|
||||
|
||||
let customRandom = (alphabet, size, getRandom) => {
|
||||
// First, a bitmask is necessary to generate the ID. The bitmask makes bytes
|
||||
// values closer to the alphabet size. The bitmask calculates the closest
|
||||
// `2^31 - 1` number, which exceeds the alphabet size.
|
||||
// For example, the bitmask for the alphabet size 30 is 31 (00011111).
|
||||
let random = bytes => {
|
||||
fillPool((bytes -= 0))
|
||||
return pool.subarray(poolOffset - bytes, poolOffset)
|
||||
}
|
||||
let customRandom = (alphabet, defaultSize, getRandom) => {
|
||||
let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1
|
||||
// Though, the bitmask solution is not perfect since the bytes exceeding
|
||||
// the alphabet size are refused. Therefore, to reliably generate the ID,
|
||||
// the random bytes redundancy has to be satisfied.
|
||||
|
||||
// Note: every hardware random generator call is performance expensive,
|
||||
// because the system call for entropy collection takes a lot of time.
|
||||
// So, to avoid additional system calls, extra bytes are requested in advance.
|
||||
|
||||
// Next, a step determines how many random bytes to generate.
|
||||
// The number of random bytes gets decided upon the ID size, mask,
|
||||
// alphabet size, and magic number 1.6 (using 1.6 peaks at performance
|
||||
// according to benchmarks).
|
||||
let step = Math.ceil((1.6 * mask * size) / alphabet.length)
|
||||
|
||||
return () => {
|
||||
let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)
|
||||
return (size = defaultSize) => {
|
||||
let id = ''
|
||||
while (true) {
|
||||
let bytes = getRandom(step)
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = step
|
||||
while (i--) {
|
||||
// Adding `|| ''` refuses a random byte that exceeds the alphabet size.
|
||||
id += alphabet[bytes[i] & mask] || ''
|
||||
// `id.length + 1 === size` is a more compact option.
|
||||
if (id.length === +size) return id
|
||||
if (id.length === size) return id
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let customAlphabet = (alphabet, size) => customRandom(alphabet, size, random)
|
||||
|
||||
let customAlphabet = (alphabet, size = 21) =>
|
||||
customRandom(alphabet, size, random)
|
||||
let nanoid = (size = 21) => {
|
||||
let bytes = random(size)
|
||||
fillPool((size -= 0))
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
while (size--) {
|
||||
// It is incorrect to use bytes exceeding the alphabet size.
|
||||
// The following mask reduces the random byte in the 0-255 value
|
||||
// range to the 0-63 value range. Therefore, adding hacks, such
|
||||
// as empty string fallback or magic numbers, is unneccessary because
|
||||
// the bitmask trims bytes down to the alphabet size.
|
||||
id += urlAlphabet[bytes[size] & 63]
|
||||
for (let i = poolOffset - size; i < poolOffset; i++) {
|
||||
id += urlAlphabet[pool[i] & 63]
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
export { nanoid, customAlphabet, customRandom, urlAlphabet, random }
|
||||
|
||||
+1
-1
@@ -1 +1 @@
|
||||
export let nanoid=(t=21)=>{let e="",r=crypto.getRandomValues(new Uint8Array(t));for(;t--;){let n=63&r[t];e+=n<36?n.toString(36):n<62?(n-26).toString(36).toUpperCase():n<63?"_":"-"}return e};
|
||||
export let nanoid=(t=21)=>crypto.getRandomValues(new Uint8Array(t)).reduce(((t,e)=>t+=(e&=63)<36?e.toString(36):e<62?(e-26).toString(36).toUpperCase():e<63?"_":"-"),"");
|
||||
+3
-12
@@ -1,30 +1,21 @@
|
||||
// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped
|
||||
// optimize the gzip compression for this alphabet.
|
||||
let urlAlphabet =
|
||||
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
|
||||
|
||||
let customAlphabet = (alphabet, size) => {
|
||||
return () => {
|
||||
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
return (size = defaultSize) => {
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = size
|
||||
while (i--) {
|
||||
// `| 0` is more compact and faster than `Math.floor()`.
|
||||
id += alphabet[(Math.random() * alphabet.length) | 0]
|
||||
}
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
let nanoid = (size = 21) => {
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = size
|
||||
while (i--) {
|
||||
// `| 0` is more compact and faster than `Math.floor()`.
|
||||
id += urlAlphabet[(Math.random() * 64) | 0]
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
module.exports = { nanoid, customAlphabet }
|
||||
|
||||
+8
-5
@@ -10,16 +10,16 @@
|
||||
* @param size Size of the ID. The default size is 21.
|
||||
* @returns A random string.
|
||||
*/
|
||||
export function nanoid (size?: number): string
|
||||
export function nanoid(size?: number): string
|
||||
|
||||
/**
|
||||
* Generate URL-friendly unique ID based on the custom alphabet.
|
||||
* Generate a unique ID based on a custom alphabet.
|
||||
* This method uses the non-secure predictable random generator
|
||||
* with bigger collision probability.
|
||||
*
|
||||
* @param alphabet Alphabet used to generate the ID.
|
||||
* @param size Size of the ID.
|
||||
* @returns A random string.
|
||||
* @param defaultSize Size of the ID. The default size is 21.
|
||||
* @returns A random string generator.
|
||||
*
|
||||
* ```js
|
||||
* import { customAlphabet } from 'nanoid/non-secure'
|
||||
@@ -27,4 +27,7 @@ export function nanoid (size?: number): string
|
||||
* model.id = //=> "8ё56а"
|
||||
* ```
|
||||
*/
|
||||
export function customAlphabet (alphabet: string, size: number): () => string
|
||||
export function customAlphabet(
|
||||
alphabet: string,
|
||||
defaultSize?: number
|
||||
): (size?: number) => string
|
||||
|
||||
+3
-12
@@ -1,30 +1,21 @@
|
||||
// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped
|
||||
// optimize the gzip compression for this alphabet.
|
||||
let urlAlphabet =
|
||||
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
|
||||
|
||||
let customAlphabet = (alphabet, size) => {
|
||||
return () => {
|
||||
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
|
||||
let customAlphabet = (alphabet, defaultSize = 21) => {
|
||||
return (size = defaultSize) => {
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = size
|
||||
while (i--) {
|
||||
// `| 0` is more compact and faster than `Math.floor()`.
|
||||
id += alphabet[(Math.random() * alphabet.length) | 0]
|
||||
}
|
||||
return id
|
||||
}
|
||||
}
|
||||
|
||||
let nanoid = (size = 21) => {
|
||||
let id = ''
|
||||
// A compact alternative for `for (var i = 0; i < step; i++)`.
|
||||
let i = size
|
||||
while (i--) {
|
||||
// `| 0` is more compact and faster than `Math.floor()`.
|
||||
id += urlAlphabet[(Math.random() * 64) | 0]
|
||||
}
|
||||
return id
|
||||
}
|
||||
|
||||
export { nanoid, customAlphabet }
|
||||
|
||||
+32
-21
@@ -1,32 +1,33 @@
|
||||
{
|
||||
"_args": [
|
||||
[
|
||||
"nanoid@3.1.10",
|
||||
"/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series"
|
||||
"nanoid@3.3.4",
|
||||
"/home/node/nuxt"
|
||||
]
|
||||
],
|
||||
"_from": "nanoid@3.1.10",
|
||||
"_id": "nanoid@3.1.10",
|
||||
"_from": "nanoid@3.3.4",
|
||||
"_id": "nanoid@3.3.4",
|
||||
"_inBundle": false,
|
||||
"_integrity": "sha512-iZFMXKeXWkxzlfmMfM91gw7YhN2sdJtixY+eZh9V6QWJWTOiurhpKhBMgr82pfzgSqglQgqYSCowEYsz8D++6w==",
|
||||
"_integrity": "sha512-MqBkQh/OHTS2egovRtLk45wEyNXwF+cokD+1YPf9u5VfJiRdAiRwB2froX5Co9Rh20xs4siNPm8naNotSD6RBw==",
|
||||
"_location": "/nanoid",
|
||||
"_phantomChildren": {},
|
||||
"_requested": {
|
||||
"type": "version",
|
||||
"registry": true,
|
||||
"raw": "nanoid@3.1.10",
|
||||
"raw": "nanoid@3.3.4",
|
||||
"name": "nanoid",
|
||||
"escapedName": "nanoid",
|
||||
"rawSpec": "3.1.10",
|
||||
"rawSpec": "3.3.4",
|
||||
"saveSpec": null,
|
||||
"fetchSpec": "3.1.10"
|
||||
"fetchSpec": "3.3.4"
|
||||
},
|
||||
"_requiredBy": [
|
||||
"/@nuxt/telemetry"
|
||||
"/@nuxt/telemetry",
|
||||
"/@vue/compiler-sfc/postcss"
|
||||
],
|
||||
"_resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.1.10.tgz",
|
||||
"_spec": "3.1.10",
|
||||
"_where": "/mnt/Foxconn/Digitalent/Deverloper/liff-push_2series",
|
||||
"_resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.4.tgz",
|
||||
"_spec": "3.3.4",
|
||||
"_where": "/home/node/nuxt",
|
||||
"author": {
|
||||
"name": "Andrey Sitnik",
|
||||
"email": "andrey@sitnik.ru"
|
||||
@@ -35,37 +36,46 @@
|
||||
"nanoid": "bin/nanoid.cjs"
|
||||
},
|
||||
"browser": {
|
||||
"./index.js": "./index.browser.js"
|
||||
"./index.js": "./index.browser.js",
|
||||
"./async/index.js": "./async/index.browser.js",
|
||||
"./async/index.cjs": "./async/index.browser.cjs",
|
||||
"./index.cjs": "./index.browser.cjs"
|
||||
},
|
||||
"bugs": {
|
||||
"url": "https://github.com/ai/nanoid/issues"
|
||||
},
|
||||
"description": "A tiny (108 bytes), secure URL-friendly unique string ID generator",
|
||||
"description": "A tiny (116 bytes), secure URL-friendly unique string ID generator",
|
||||
"engines": {
|
||||
"node": "^10 || ^12 || >=13.7"
|
||||
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
|
||||
},
|
||||
"exports": {
|
||||
"./package.json": "./package.json",
|
||||
".": {
|
||||
"types": "./index.d.ts",
|
||||
"browser": "./index.browser.js",
|
||||
"require": "./index.cjs",
|
||||
"import": "./index.js"
|
||||
"import": "./index.js",
|
||||
"default": "./index.js"
|
||||
},
|
||||
"./index.d.ts": "./index.d.ts",
|
||||
"./package.json": "./package.json",
|
||||
"./async/package.json": "./async/package.json",
|
||||
"./async": {
|
||||
"browser": "./async/index.browser.js",
|
||||
"require": "./async/index.cjs",
|
||||
"import": "./async/index.js"
|
||||
"import": "./async/index.js",
|
||||
"default": "./async/index.js"
|
||||
},
|
||||
"./non-secure/package.json": "./non-secure/package.json",
|
||||
"./non-secure": {
|
||||
"require": "./non-secure/index.cjs",
|
||||
"import": "./non-secure/index.js"
|
||||
"import": "./non-secure/index.js",
|
||||
"default": "./non-secure/index.js"
|
||||
},
|
||||
"./url-alphabet/package.json": "./url-alphabet/package.json",
|
||||
"./url-alphabet": {
|
||||
"require": "./url-alphabet/index.cjs",
|
||||
"import": "./url-alphabet/index.js"
|
||||
"import": "./url-alphabet/index.js",
|
||||
"default": "./url-alphabet/index.js"
|
||||
}
|
||||
},
|
||||
"homepage": "https://github.com/ai/nanoid#readme",
|
||||
@@ -86,5 +96,6 @@
|
||||
},
|
||||
"sideEffects": false,
|
||||
"type": "module",
|
||||
"version": "3.1.10"
|
||||
"types": "./index.d.ts",
|
||||
"version": "3.3.4"
|
||||
}
|
||||
|
||||
+1
-4
@@ -1,6 +1,3 @@
|
||||
// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped
|
||||
// optimize the gzip compression for this alphabet.
|
||||
let urlAlphabet =
|
||||
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
|
||||
|
||||
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
|
||||
module.exports = { urlAlphabet }
|
||||
|
||||
+1
-4
@@ -1,6 +1,3 @@
|
||||
// This alphabet uses `A-Za-z0-9_-` symbols. The genetic algorithm helped
|
||||
// optimize the gzip compression for this alphabet.
|
||||
let urlAlphabet =
|
||||
'ModuleSymbhasOwnPr-0123456789ABCDEFGHNRVfgctiUvz_KqYTJkLxpZXIjQW'
|
||||
|
||||
'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict'
|
||||
export { urlAlphabet }
|
||||
|
||||
Reference in New Issue
Block a user