pax_global_header00006660000000000000000000000064146045464610014524gustar00rootroot0000000000000052 comment=4d0036fb45febee7ba0256cc22ba6a2cd1dc1583 nanoid-5.0.7/000077500000000000000000000000001460454646100130055ustar00rootroot00000000000000nanoid-5.0.7/.editorconfig000066400000000000000000000002231460454646100154570ustar00rootroot00000000000000root = true [*] indent_style = space indent_size = 2 end_of_line = lf charset = utf-8 trim_trailing_whitespace = true insert_final_newline = true nanoid-5.0.7/.github/000077500000000000000000000000001460454646100143455ustar00rootroot00000000000000nanoid-5.0.7/.github/FUNDING.yml000066400000000000000000000000401460454646100161540ustar00rootroot00000000000000tidelift: npm/nanoid github: ai nanoid-5.0.7/.github/workflows/000077500000000000000000000000001460454646100164025ustar00rootroot00000000000000nanoid-5.0.7/.github/workflows/release.yml000066400000000000000000000025511460454646100205500ustar00rootroot00000000000000name: Release on: push: tags: - '*' permissions: contents: write jobs: release: name: Release On Tag if: startsWith(github.ref, 'refs/tags/') runs-on: ubuntu-latest steps: - name: Checkout the repository uses: actions/checkout@v4 - name: Extract the changelog id: changelog run: | TAG_NAME=${GITHUB_REF/refs\/tags\//} READ_SECTION=false CHANGELOG="" while IFS= read -r line; do if [[ "$line" =~ ^#+\ +(.*) ]]; then if [[ "${BASH_REMATCH[1]}" == "$TAG_NAME" ]]; then READ_SECTION=true elif [[ "$READ_SECTION" == true ]]; then break fi elif [[ "$READ_SECTION" == true ]]; then CHANGELOG+="$line"$'\n' fi done < "CHANGELOG.md" CHANGELOG=$(echo "$CHANGELOG" | awk '/./ {$1=$1;print}') echo "changelog_content<> $GITHUB_OUTPUT echo "$CHANGELOG" >> $GITHUB_OUTPUT echo "EOF" >> $GITHUB_OUTPUT - name: Create the release if: steps.changelog.outputs.changelog_content != '' uses: softprops/action-gh-release@v1 with: name: ${{ github.ref_name }} body: '${{ steps.changelog.outputs.changelog_content }}' draft: false prerelease: false nanoid-5.0.7/.github/workflows/test.yml000066400000000000000000000033521460454646100201070ustar00rootroot00000000000000name: Test on: push: branches: - main pull_request: permissions: contents: read jobs: full: name: Node.js Latest Full runs-on: ubuntu-latest steps: - name: Checkout the repository uses: actions/checkout@v4 - name: Install pnpm uses: pnpm/action-setup@v3 with: version: 8 - name: Install Node.js uses: actions/setup-node@v4 with: node-version: 21 cache: pnpm - name: Install dependencies run: pnpm install --ignore-scripts - name: Run tests run: pnpm test short: runs-on: ubuntu-latest strategy: matrix: node-version: - 20 - 18 name: Node.js ${{ matrix.node-version }} Quick steps: - name: Checkout the repository uses: actions/checkout@v4 - name: Install pnpm uses: pnpm/action-setup@v3 with: version: 8 - name: Install Node.js ${{ matrix.node-version }} uses: actions/setup-node@v4 with: node-version: ${{ matrix.node-version }} cache: pnpm - name: Install dependencies run: pnpm install --ignore-scripts - name: Run unit tests run: pnpm bnt benchmark: name: Benchmark runs-on: ubuntu-latest steps: - name: Checkout the repository uses: actions/checkout@v4 - name: Install pnpm uses: pnpm/action-setup@v3 with: version: 8 - name: Install Node.js uses: actions/setup-node@v4 with: node-version: 20 cache: pnpm - name: Install dependencies run: pnpm install --ignore-scripts - name: Run benchmark run: node ./test/benchmark.js nanoid-5.0.7/.gitignore000066400000000000000000000000311460454646100147670ustar00rootroot00000000000000node_modules/ coverage/ nanoid-5.0.7/.npmignore000066400000000000000000000000441460454646100150020ustar00rootroot00000000000000test/ tsconfig.json coverage/ img/ nanoid-5.0.7/CHANGELOG.md000066400000000000000000000161101460454646100146150ustar00rootroot00000000000000# Change Log This project adheres to [Semantic Versioning](http://semver.org/). ## 5.0.7 * Fixed Parcel support (by @WilhelmYakunin). ## 5.0.6 * Fixed React Native support. ## 5.0.5 * Make browser’s version faster by increasing size a little (by Samuel Elgozi). ## 5.0.4 * Fixed CLI docs (by @ilyaboka). ## 5.0.3 * Fixed CLI docs (by Chris Schmich). ## 5.0.2 * Fixed `webcrypto` import (by Divyansh Singh). ## 5.0.1 * Fixed Node.js 18 support. ## 5.0 * Moved Node.js version to Web Crypto API. * Removed async API since Web Crypto API has only sync version. * Removed Node.js 14 and 16 support. ## 4.0.2 * Added [link](https://github.com/sponsors/ai) to Github Sponsors. ## 4.0.1 * Reduced npm package size (by @HiChen404). ## 4.0 * Removed CommonJS support. Nano ID 4 will work only with ESM applications. We will support 3.x branch with CommonJS for users who can’t migrate to ESM. * Removed Node.js 10 and Node.js 12 support. * Reduced npm package size. ## 3.3.7 * Fixed `node16` TypeScript support (by Saadi Myftija). ## 3.3.6 * Fixed package. ## 3.3.5 * Backport funding information. ## 3.3.4 * Fixed `--help` in CLI (by @Lete114). ## 3.3.3 * Reduced size (by Anton Khlynovskiy). ## 3.3.2 * Fixed `enhanced-resolve` support. ## 3.3.1 * Reduced package size. ## 3.3 * Added `size` argument to function from `customAlphabet` (by Stefan Sundin). ## 3.2 * Added `--size` and `--alphabet` arguments to binary (by Vitaly Baev). ## 3.1.32 * Reduced `async` exports size (by Artyom Arutyunyan). * Moved from Jest to uvu (by Vitaly Baev). ## 3.1.31 * Fixed collision vulnerability on object in `size` (by Artyom Arutyunyan). ## 3.1.30 * Reduced size for project with `brotli` compression (by Anton Khlynovskiy). ## 3.1.29 * Reduced npm package size. ## 3.1.28 * Reduced npm package size. ## 3.1.27 * Cleaned `dependencies` from development tools. ## 3.1.26 * Improved performance (by Eitan Har-Shoshanim). * Reduced npm package size. ## 3.1.25 * Fixed `browserify` support. ## 3.1.24 * Fixed `browserify` support (by Artur Paikin). ## 3.1.23 * Fixed `esbuild` support. ## 3.1.22 * Added `default` and `browser.default` to `package.exports`. ## 3.1.21 * Reduced npm package size. ## 3.1.20 * Fix ES modules support. ## 3.1.19 * Reduced `customAlphabet` size (by Enrico Scherlies). ## 3.1.18 * Fixed `package.exports`. ## 3.1.17 * Added files without `process`. ## 3.1.16 * Speeded up Nano ID 4 times (by Peter Boyer). ## 3.1.15 * Fixed `package.types` path. ## 3.1.14 * Added `package.types`. ## 3.1.13 * Removed Node.js 15.0.0 with `randomFillSync` regression from `engines.node`. ## 3.1.12 * Improved IE 11 docs. ## 3.1.11 * Fixed asynchronous `customAlphabet` in browser (by @LoneRifle). ## 3.1.10 * Fix ES modules support. ## 3.1.9 * Try to fix React Native Expo support. ## 3.1.8 * Add React Native Expo support. ## 3.1.7 * Clean up code. ## 3.1.6 * Avoid `self` using. ## 3.1.5 * Improve IE docs and warning. ## 3.1.4 * Restrict old Node.js 13 by `engines.node` (by Cansin Yildiz). ## 3.1.3 * Fix ES modules issue with CLI. ## 3.1.2 * Add shebang to CLI. ## 3.1.1 * Fix CLI. ## 3.1 * Add `npx nanoid` CLI. ## 3.0.2 * Fix docs (by Dylan Irlbeck ). ## 3.0.1 * Fix React Native warning on `non-secure` import (by Jia Huang). ## 3.0 **Migration guide:** * Move to ES2016 syntax. You need to use Babel for IE 11. * Move to named exports `import { nanoid } from 'nanoid'`. * Move `import url from 'nanoid/url'` to `import { urlAlphabet } from 'nanoid'`. * Replace `format()` to `customRandom()`. * Replace `generate()` to `customAlphabet()`. * Remove `async/format`. * Remove React Native support for `nanoid/async`. * Add `nanoid.js` to use directly in browser from CDN. * Add TypeScript type definitions. * Add ES modules support for bundlers, Node.js, and React Native. * Fix React Native support. * Reduce size. * Improve docs (by Dair Aidarkhanov). ## 2.1.11 * Reduce size (by Anton Evzhakov). ## 2.1.10 * Reduce size by 10% (by Anton Khlynovskiy). ## 2.1.9 * Reduce `format` and `async/format` size (by Dair Aidarkhanov). ## 2.1.8 * Improve React docs (by Nahum Zsilva). ## 2.1.7 * Reduce `index`, `async` and `non-secure` size (by @polemius). ## 2.1.6 * Reduce size (by Stas Lashmanov). * Return fast mask for Node.js. ## 2.1.5 * Reduce size (by Max Graey). * Fix IE support. ## 2.1.4 * Reduce `generate` size (by Vsevolod Rodionov). * Reduce `format` and `format` size (by Victor). * Reduce `async`, `non-secure` and `non-secure/generate` size. * Speed up `format` and `async/format` (by Max Graey). * Improve development process on Windows (by Stanislav Lashmanov). ## 2.1.3 * Improve performance (by Stephen Richardson). * Reduce size (by Stephen Richardson). ## 2.1.2 * Improve docs. ## 2.1.1 * Fix React Native support (by Shawn Hwei). ## 2.1 * Improve React Native support (by Sebastian Werner). ## 2.0.4 * Improve error text for React Native (by Sebastian Werner). ## 2.0.3 * Fix freeze on string in ID length. ## 2.0.2 * Improve docs (by Sylvanus Kateile and Mark Stosberg). ## 2.0.1 * Reduce npm package size. * Mark package as not having side effects (by @xiaody). ## 2.0 * Use `-` instead of `~` in default alphabet to by file name safe. * Add `nanoid/non-secure/generate`. ## 1.3.4 * Reduce `non-secure` size. * Add `async` callback type check. ## 1.3.3 * Fix `nanoid/async` performance regression. * Fix old Node.js `not seeded` issue in synchronous version too. ## 1.3.2 * Fix random generator `not seeded` issue of old Node.js. ## 1.3.1 * Reduce library size. ## 1.3 * Add `nanoid/async/format` and `nanoid/async/generate`. * Improve synchronous API performance. * Reduce `url` size (by Daniil Poroshin). * Improve React Native docs (by joelgetaction). ## 1.2.6 * Reduce library size (by rqrqrqrq). ## 1.2.5 * Fix Node.js 6.11.1 support (by Andrey Belym). ## 1.2.4 * Speed up Node.js secure generators (by Dmitriy Tsvettsikh). ## 1.2.3 * Fix JSDoc (by Hendry Sadrak). ## 1.2.2 * Fix distribution in `nanoid/non-secure` (by Eatall). ## 1.2.1 * Fix old Node.js support. ## 1.2 * Add `nanoid/async`. * Fix `nanoid/non-secure` JSDoc. * Add Chinese documentation (by Wenliang Dai). * Speed up and reduce size of `nanoid/non-secure` (by Ori Livni). ## 1.1.1 * Improve performance and reduce size of non-secure ID generator. ## 1.1 * Add non-secure ID generator. * Suggest to use non-secure ID generator for React Native developers. * Reduce size. ## 1.0.7 * Fix documentation. ## 1.0.6 * Fix documentation. ## 1.0.5 * Reduce `nanoid/index` size (by Anton Khlynovskiy). ## 1.0.4 * Reduce npm package size. ## 1.0.3 * Reduce npm package size. ## 1.0.2 * Fix Web Workers support (by Zachary Golba). ## 1.0.1 * Reduce `nanoid/index` size (by Anton Khlynovskiy). ## 1.0 * Use 21 symbols by default (by David Klebanoff). ## 0.2.2 * Reduce `nanoid/generate` size (by Anton Khlynovskiy). * Speed up Node.js random generator. ## 0.2.1 * Fix documentation (by Piper Chester). ## 0.2 * Add `size` argument to `nanoid()`. * Improve performance by 50%. * Reduce library size by 26% (by Vsevolod Rodionov and Oleg Mokhov). ## 0.1.1 * Reduce library size by 5%. ## 0.1 * Initial release. nanoid-5.0.7/LICENSE000066400000000000000000000021071460454646100140120ustar00rootroot00000000000000The MIT License (MIT) Copyright 2017 Andrey Sitnik Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. nanoid-5.0.7/README.id-ID.md000066400000000000000000000343271460454646100151620ustar00rootroot00000000000000# Nano ID Logo Nano ID oleh Anton Lovchikov [English](./README.md) | [Русский](./README.ru.md) | [简体中文](./README.zh-CN.md) | **Bahasa Indonesia** Sebuah generator ID yang unik dalam bentuk string yang ringan, aman, serta _URL-friendly_ untuk JavaScript. > "Sebuah tingkat kesempurnaan yang luar biasa, > yang mana tidak mungkin untuk tidak dihormati." - **Ringan.** Hanya 116 bytes (diperkecil dan brotlied). Tidak ada ketergantungan (dependencies) apapun. [Size Limit](https://github.com/ai/size-limit) mengatur ukuran dari generator ini. - **Aman.** Nano ID menggunakan RNG yang terdapat pada perangkat keras. Dapat digunakan dalam lingkungan seperti klaster. - **ID yang pendek.** Nano ID menggunakan alfabet yang lebih banyak ketimbang UUID (`A-Za-z0-9_-`), karenanya ukuran ID menjadi berkurang dari 36 menjadi 21 simbol. - **Portabel.** Nano ID telah dimigrasi untuk [20 bahasa pemrograman lainnya](#bahasa-pemrograman-lainnya). ```js import { nanoid } from 'nanoid' model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" ``` Mendukung penjelajah (browser) modern, IE [dengan Babel](https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/), Node.js, dan React Native. ---   Made in Evil Martians, product consulting for developer tools. --- ## Table of Contents - [Perbandingan dengan UUID](#perbandingan-dengan-uuid) - [Benchmark](#benchmark) - [Keamanan](#keamanan) - [Instalasi](#instalasi) - [API](#api) - [Blocking](#blocking) - [Non-Secure](#non-secure) - [Alfabet dan Ukuran (Custom)](#alfabet-dan-ukuran-penyesuaian) - [Generasi Random Bytes (Custom)](#generasi-random-bytes-custom) - [Penggunaan](#penggunaan) - [React](#react) - [React Native](#react-native) - [PouchDB dan CouchDB](#pouchdb-dan-couchdb) - [Web Workers](#web-workers) - [CLI](#cli) - [Bahasa Pemrograman Lainnya](#bahasa-pemrograman-lainnya) - [Alat](#alat) ## Perbandingan dengan UUID Nano ID dapat dibandingkan dengan UUID v4 (yang berbasis acak / _randomly generated_). Nano ID dan UUID v4 memiliki jumlah bita yang mirip pada ID yang dihasilkan (126 bita pada NanoID dan 122 bita pada UUID), karenanya ia memiliki probabilitas _collision_ (konflik / tabrakan) yang hampir serupa: > Agar timbul kemungkinan collison / duplikasi ID satu dalam satu miliar, perlu dihasilkan 103 triliun UUID v4. Ada dua buah perbedaan antara Nano ID dan UUID v4: 1. Nano ID menggunakan alfabet yang lebih lebar, karenanya jumlah bita acak dapat 'dikemas' dalam 21 simbol, bukan 36 simbol. 2. Kode sumber Nano ID **empat kali lebih kecil** ketimbang `uuid/v4`: 130 bytes dibanding 423 bytes. ## Benchmark ```rust $ node ./test/benchmark.js crypto.randomUUID 28,398,328 ops/sec uuid v4 10,254,199 ops/sec @napi-rs/uuid 15,110,625 ops/sec uid/secure 10,388,842 ops/sec @lukeed/uuid 8,914,507 ops/sec nanoid 7,484,029 ops/sec customAlphabet 4,867,017 ops/sec nanoid for browser 609,426 ops/sec secure-random-string 539,080 ops/sec uid-safe.sync 533,944 ops/sec shortid 59,609 ops/sec Non-secure: uid 95,579,977 ops/sec nanoid/non-secure 3,999,766 ops/sec rndm 3,981,914 ops/sec ``` Konfigurasi pengujian: Framework 13 7840U, Fedora 39, Node.js 21.6. ## Keamanan _Lihat artikel yang informatif tentang teori angka acak: [Nilai acak yang aman dalam Node.js (English)](https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba)_. - **Ketidakpastian.** Sebagai ganti untuk penggunaan `Math.random()`, Nano ID menggunakan modul `crypto` yang ada di dalam Nodejs dan/atau Web Crypto API dalam penjelajah (_browser_). Modul-modul ini menggunakan generator acak berbasis perangkat keras yang tidak bisa diprediksi untuk mendapatkan nilai-nilai yang tidak pasti yang aman secara kriptografis. - **Keseragaman.** Pembagian dengan rumus `random % alphabet` adalah kesalahan yang seringkali dilakukan ketika merancang sebuah generator ID. Distribusi dari nilai-nilai tersebut tidak akan seimbang; dalam artian ada kesempatan untuk beberapa simbol untuk muncul dibandingkan dengan simbol yang lain. Ini memiliki dampak yang kurang baik, yakni mengurangi jumlah percobaan ketika seseorang mencoba untuk melakukan _brute-force attacks_. Nano ID menggunakan [algoritma yang lebih baik](https://github.com/ai/nanoid/blob/main/index.js) dan sudah diuji untuk keseragamannya. Nano ID uniformity - **Terdokumentasi secara baik.** Seluruh algoritma Nano ID sudah terdokumentasi. Lihat komentar di [kode sumber](https://github.com/ai/nanoid/blob/main/index.js). - **Kerentanan.** Untuk melaporkan sebuah _security vulnerability_ atau kerentanan, mohon menggunakan [Tidelift Security Contact](https://tidelift.com/security). Tidelift akan mengkoordinasikan pembetulan dan penyingkapan dari kerentanan tersebut. ## Instalasi ```bash npm install nanoid ``` Nano ID 5 hanya tersedia untuk proyek, pengujian, atau skrip ESM Node.js. Untuk CommonJS Anda memerlukan Nano ID 3.x (kami masih mendukungnya): ```bash npm install nanoid@3 ``` Apabila ingin 'coba-coba' terlebih dahulu, dapat digunakan Nano ID melalui CDN. Hal ini tidak direkomendasikan untuk digunakan pada lingkungan produksi karena performa pemuatan (_loading_) yang berkurang. ```js import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js' ``` ## API Nano ID memiliki dua API: normal dan _non-secure_. Bawaannya, Nano ID menggunakan simbol yang _URL-friendly_ (`A-Za-z0-9_-`) dan mengembalikan ID dengan 21 karakter (untuk memiliki probabilitas collision / tabrakan yang mirip dengan UUID v4). ### Blocking Penggunaan Nano ID yang aman dan yang paling mudah. Dalam kasus langka, fungsi ini dapat menghambat CPU untuk melakukan proses yang lain ketika dalam proses 'noise-collection' untuk generasi nilai acak (yang dilakukan pada perangkat keras). ```js import { nanoid } from 'nanoid' model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" ``` Apabila ingin mengurangi ukuran ID (dan meningkatkan probabilitas collision), dapat dimasukkan `size` sebagai argumen dari fungsi `nanoid()`. ```js nanoid(10) //=> "IRFa-VaY2b" ``` Jangan lupa memeriksa tingkat keamanan dari ukuran ID dalam situs [ID collision probability calculator](https://zelark.github.io/nano-id-cc/). Dapat digunakan pula [custom alphabet](#custom-alphabet-or-size) atau [random generator](#custom-random-bytes-generator) yang lain. ### Non-Secure Konfigurasi bawaan Nano ID menggunakan random bytes generator yang berasal dari perangkat keras untuk keamanan dan probabilitas collision yang rendah. Apabila tidak terlalu memikirkan soal keamanan, dapat pula menggunakan non-secure generator yang lebih cepat. ```js import { nanoid } from 'nanoid/non-secure' const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ" ``` ### Alfabet dan Ukuran (Custom) `customAlphabet` digunakan untuk membuat Nano ID dengan alfabet dan ukuran ID yang sesuai dengan kebutuhan (dapat dikustomisasi). ```js import { customAlphabet } from 'nanoid' const nanoid = customAlphabet('1234567890abcdef', 10) model.id = nanoid() //=> "4f90d13a42" ``` Ketika menggunakan fungsi ini, jangan lupa untuk memeriksa keamanan alfabet dan ukuran ID dalam [ID collision probability calculator](https://alex7kom.github.io/nano-nanoid-cc/). Untuk lebih banyak alfabet, dapat menggunakan [`nanoid-dictionary`](https://github.com/CyberAP/nanoid-dictionary). Alfabet harus terbentuk dari 256 simbol atau lebih kecil. Selain itu, keamanan algoritma generasi yang berada di dalam library ini tidak dijamin aman. API non-secure yang dapat dikustomisasi dengan `customAlphabet` pun tersedia disini: ```js import { customAlphabet } from 'nanoid/non-secure' const nanoid = customAlphabet('1234567890abcdef', 10) user.id = nanoid() ``` ### Generasi Random Bytes (Custom) `customRandom` digunakan untuk membuat Nano ID yang mengganti alfabet dan algoritma _random bytes generator_ yang telah diimplementasikan pada versi bawaan (dalam artian menggunakan algoritma sendiri untuk mendapatkan random bytes). Pada contoh berikut, digunakan _seed-based generator_: ```js import { customRandom } from 'nanoid' const rng = seedrandom(seed) const nanoid = customRandom('abcdef', 10, size => { return new Uint8Array(size).map(() => 256 * rng()) }) nanoid() //=> "fbaefaadeb" ``` Fungsi _callback_ pada `random` harus menerima ukuran array dan mengembalikan sebuah array dengan angka acak. Apabila ingin menggunakan alfabet bawaan NanoID pada fungsi `customRandom`, dapat menggunakan konstanta `urlAlphabet` seperti berikut: ```js const { customRandom, urlAlphabet } = require('nanoid') const nanoid = customRandom(urlAlphabet, 10, random) ``` API asinkronus dan non-secure tidak tersedia untuk fungsi `customRandom`. ## Penggunaan ### React Dalam React, tidak ada cara yang benar bila ingin menggunakan Nano ID untuk prop `key`, karena `key` tersebut harus konsisten dalam setiap proses render yang terjadi. ```jsx function Todos({ todos }) { return (
    {todos.map(todo => ( /* JANGAN DILAKUKAN! */
  • {todo.text}
  • ))}
) } ``` Karena hal tersebut, disarankan untuk menggunakan ID yang stabil pada setiap objek yang di-render oleh React. ```jsx const todoItems = todos.map(todo =>
  • {todo.text}
  • ) ``` Apabila tidak memiliki ID yang stabil pada setiap _item_ yang di-render pada React, lebih baik menggunakan indeks sebuah array sebagai `key` ketimbang menggunakan fungsi `nanoid()`, seperti berikut: ```jsx const todoItems = todos.map((text, index) => ( /* Tetap tidak direkomendasikan, tetapi lebih disarankan dari 'nanoid()'. Lakukan ini apabila setiap objek / item dalam list tidak ada ID yang stabil. */
  • {text}
  • )) ``` ### React Native React Native tidak memiliki _built-in random generator_. Digunakan polyfill seperti berikut yang berjalan untuk React Native dan Expo yang bermula dari versi `39.x`. 1. Periksa dokumentasi [`react-native-get-random-values`](https://github.com/LinusU/react-native-get-random-values) dan install di aplikasi. 2. Import library tersebut sebelum Nano ID. ```js import 'react-native-get-random-values' import { nanoid } from 'nanoid' ``` ### PouchDB dan CouchDB Dalam PouchDB dan CouchDB, ID tidak bisa dimulai dengan underscore `_`. Sebuah _prefix_ dibutuhkan untuk mencegah hal ini terjadi, karena Nano ID mungkin menggunakan `_` sebagai karakter pertama dari ID yang dihasilkan. ID bawaan dapat diubah dengan opsi berikut: ```js db.put({ _id: 'id' + nanoid(), … }) ``` ### Web Workers Web Workers tidak memiliki akses untuk secure random generator. Keamanan sangat penting pada ID yang mana setiap ID harus memiliki sifat tidak bisa diprediksi, seperti pada contoh use-case generasi link pada "access by URL". Apabila tidak memerlukan ID yang tidak bisa diprediksi, tetapi ingin/harus menggunakan Web Workers, dapat digunakan NanoID dengan API non-secure. ```js import { nanoid } from 'nanoid/non-secure' nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ" ``` Perhatian: ID yang dihasilkan dari non-secure dapat lebih mudah tabrakan / memiliki probabilitas collision yang lebih besar. ### CLI Nano ID dapat didapatkan dengan cara menggunakan `npx nanoid` pada Terminal. Hanya diperlukan Node.js untuk ini, dan tidak perlu mengunduh dan menginstall Nano ID dalam sistem. ```sh $ npx nanoid npx: installed 1 in 0.63s LZfXLFzPPR4NNrgjlWDxn ``` Bila ingin mengganti alfabet atau ukuran ID, dapat menggunakan [`nanoid-cli`](https://github.com/twhitbeck/nanoid-cli). ### Bahasa Pemrograman Lainnya Nano ID telah bermigrasi ke berbagai macam bahasa. Seluruh versi dapat digunakan untuk mendapatkan ID generator yang sama pada sisi klien dan sisi penyedia layanan (_client-side_ dan _server-side_). - [C#](https://github.com/codeyu/nanoid-net) - [C++](https://github.com/mcmikecreations/nanoid_cpp) - [Clojure and ClojureScript](https://github.com/zelark/nano-id) - [ColdFusion/CFML](https://github.com/JamoCA/cfml-nanoid) - [Crystal](https://github.com/mamantoha/nanoid.cr) - [Dart & Flutter](https://github.com/pd4d10/nanoid-dart) - [Deno](https://github.com/ianfabs/nanoid) - [Elixir](https://github.com/railsmechanic/nanoid) - [Go](https://github.com/jaevor/go-nanoid) - [Haskell](https://github.com/MichelBoucey/NanoID) - [Haxe](https://github.com/flashultra/uuid) - [Janet](https://sr.ht/~statianzo/janet-nanoid/) - [Java](https://github.com/aventrix/jnanoid) - [Kotlin](https://github.com/viascom/nanoid-kotlin) - [MySQL/MariaDB](https://github.com/viascom/nanoid-mysql-mariadb) - [Nim](https://github.com/icyphox/nanoid.nim) - [OCaml](https://github.com/routineco/ocaml-nanoid) - [Perl](https://github.com/tkzwtks/Nanoid-perl) - [PHP](https://github.com/hidehalo/nanoid-php) - [Python](https://github.com/puyuan/py-nanoid) with [dictionaries](https://pypi.org/project/nanoid-dictionary) - [Postgres Extension](https://github.com/spa5k/uids-postgres) - [Postgres Native Function](https://github.com/viascom/nanoid-postgres) - [R](https://github.com/hrbrmstr/nanoid) (with dictionaries) - [Ruby](https://github.com/radeno/nanoid.rb) - [Rust](https://github.com/nikolay-govorov/nanoid) - [Swift](https://github.com/antiflasher/NanoID) - [Unison](https://share.unison-lang.org/latest/namespaces/hojberg/nanoid) - [V](https://github.com/invipal/nanoid) - [Zig](https://github.com/SasLuca/zig-nanoid) Untuk environment lainnya, [CLI](#cli) tersedia untuk melakukan generasi ID dari command line / Terminal. ## Alat - [ID Size Calculator](https://zelark.github.io/nano-id-cc/) menunjukkan probabilitas collision ketika melakukan konfigurasi alfabet dan ukuran. - [`nanoid-dictionary`](https://github.com/CyberAP/nanoid-dictionary) untuk menggunakan alfabet popular dalam fungsi [`customAlphabet`](#custom-alphabet-or-size) - [`nanoid-good`](https://github.com/y-gagar1n/nanoid-good) untuk meyakinkan bahwa ID yang di-generasi tidak memiliki kata-kata yang kurang baik (kasar, tidak sopan, dsb.). nanoid-5.0.7/README.md000066400000000000000000000323241460454646100142700ustar00rootroot00000000000000# Nano ID Nano ID logo by Anton Lovchikov **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.** 116 bytes (minified and brotlied). No dependencies. [Size Limit] controls the size. * **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 over [20 programming languages](./README.md#other-programming-languages). ```js import { nanoid } from 'nanoid' model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" ``` ---   Made in Evil Martians, product consulting for developer tools. --- [online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ [with Babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ [Size Limit]: https://github.com/ai/size-limit ## Table of Contents * [Comparison with UUID](#comparison-with-uuid) * [Benchmark](#benchmark) * [Security](#security) * [Install](#install) * [API](#api) * [Blocking](#blocking) * [Non-Secure](#non-secure) * [Custom Alphabet or Size](#custom-alphabet-or-size) * [Custom Random Bytes Generator](#custom-random-bytes-generator) * [Usage](#usage) * [React](#react) * [React Native](#react-native) * [PouchDB and CouchDB](#pouchdb-and-couchdb) * [Web Workers](#web-workers) * [CLI](#cli) * [Other Programming Languages](#other-programming-languages) * [Tools](#tools) ## 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 two 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 **4 times smaller** than `uuid/v4` package: 130 bytes instead of 423. ## Benchmark ```rust $ node ./test/benchmark.js crypto.randomUUID 28,398,328 ops/sec uuid v4 10,254,199 ops/sec @napi-rs/uuid 15,110,625 ops/sec uid/secure 10,388,842 ops/sec @lukeed/uuid 8,914,507 ops/sec nanoid 7,484,029 ops/sec customAlphabet 4,867,017 ops/sec nanoid for browser 609,426 ops/sec secure-random-string 539,080 ops/sec uid-safe.sync 533,944 ops/sec shortid 59,609 ops/sec Non-secure: uid 95,579,977 ops/sec nanoid/non-secure 3,999,766 ops/sec rndm 3,981,914 ops/sec ``` Test configuration: Framework 13 7840U, Fedora 39, Node.js 21.6. ## 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. Nano ID uniformity * **Well-documented:** all Nano ID hacks are documented. See comments in [the source]. * **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/main/index.js [the source]: https://github.com/ai/nanoid/blob/main/index.js ## Install ```bash npm install nanoid ``` Nano ID 5 works only with ESM projects, in tests or Node.js scripts. For CommonJS you need Nano ID 3.x (we still support it): ```bash npm install nanoid@3 ``` For quick hacks, you can load Nano ID from CDN. 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' ``` ## API Nano ID has 2 APIs: normal and non-secure. By default, Nano ID uses URL-friendly symbols (`A-Za-z0-9_-`) and returns an ID with 21 characters (to have a collision probability similar to UUID v4). ### Blocking The safe and easiest way to use Nano ID. In rare cases could block CPU from other work while noise collection for hardware random generator. ```js import { nanoid } from 'nanoid' model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" ``` 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/ ### 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, you can use it for environments without hardware random generators. ```js import { nanoid } from 'nanoid/non-secure' const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ" ``` ### Custom Alphabet or Size `customAlphabet` returns a function that 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" ``` ```js import { customAlphabet } from 'nanoid/non-secure' const nanoid = customAlphabet('1234567890abcdef', 10) user.id = nanoid() ``` 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. In addition to setting a default size, you can change the ID size when calling the function: ```js import { customAlphabet } from 'nanoid' const nanoid = customAlphabet('1234567890abcdef', 10) model.id = nanoid(5) //=> "f01a2" ``` [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) ``` Note, that between Nano ID versions we may change random generator call sequence. If you are using seed-based generators, we do not guarantee the same result. ## Usage ### React There’s no correct way to use Nano ID for React `key` prop since it should be consistent among renders. ```jsx function Todos({todos}) { return (
      {todos.map(todo => (
    • /* DON’T DO IT */ {todo.text}
    • ))}
    ) } ``` You should rather try to reach for stable ID inside your list item. ```jsx const todoItems = todos.map((todo) =>
  • {todo.text}
  • ) ``` In case you don’t have stable IDs you'd rather use index as `key` instead of `nanoid()`: ```jsx const todoItems = todos.map((text, index) =>
  • /* Still not recommended but preferred over nanoid(). Only do this if items have no stable IDs. */ {text}
  • ) ``` In case you just need random IDs to link elements like labels and input fields together, [`useId`] is recommended. That hook was added in React 18. [`useId`]: https://reactjs.org/docs/hooks-reference.html#useid ### React Native React Native does not have built-in random generator. The following polyfill works for plain React Native and Expo starting with `39.x`. 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' ``` [`react-native-get-random-values`]: https://github.com/LinusU/react-native-get-random-values ### 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(), … }) ``` ### 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 ``` Size of generated ID can be specified with `--size` (or `-s`) option: ```sh $ npx nanoid --size 10 L3til0JS4z ``` Custom alphabet can be specified with `--alphabet` (or `-a`) option (note that in this case `--size` is required): ```sh $ npx nanoid --alphabet abc --size 15 bccbcabaabaccab ``` ### 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) * [C++](https://github.com/mcmikecreations/nanoid_cpp) * [Clojure and ClojureScript](https://github.com/zelark/nano-id) * [ColdFusion/CFML](https://github.com/JamoCA/cfml-nanoid) * [Crystal](https://github.com/mamantoha/nanoid.cr) * [Dart & Flutter](https://github.com/pd4d10/nanoid-dart) * [Deno](https://github.com/ianfabs/nanoid) * [Elixir](https://github.com/railsmechanic/nanoid) * [Go](https://github.com/matoous/go-nanoid) * [Haskell](https://github.com/MichelBoucey/NanoID) * [Haxe](https://github.com/flashultra/uuid) * [Janet](https://sr.ht/~statianzo/janet-nanoid/) * [Java](https://github.com/aventrix/jnanoid) * [Kotlin](https://github.com/viascom/nanoid-kotlin) * [MySQL/MariaDB](https://github.com/viascom/nanoid-mysql-mariadb) * [Nim](https://github.com/icyphox/nanoid.nim) * [OCaml](https://github.com/routineco/ocaml-nanoid) * [Perl](https://github.com/tkzwtks/Nanoid-perl) * [PHP](https://github.com/hidehalo/nanoid-php) * [Python](https://github.com/puyuan/py-nanoid) with [dictionaries](https://pypi.org/project/nanoid-dictionary) * Postgres [Extension](https://github.com/spa5k/uids-postgres) and [Native Function](https://github.com/viascom/nanoid-postgres) * [R](https://github.com/hrbrmstr/nanoid) (with dictionaries) * [Ruby](https://github.com/radeno/nanoid.rb) * [Rust](https://github.com/nikolay-govorov/nanoid) * [Swift](https://github.com/antiflasher/NanoID) * [Unison](https://share.unison-lang.org/latest/namespaces/hojberg/nanoid) * [V](https://github.com/invipal/nanoid) * [Zig](https://github.com/SasLuca/zig-nanoid) For other environments, [CLI] is available to generate IDs from a command line. [CLI]: #cli ## 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/ [`customAlphabet`]: #custom-alphabet-or-size [`nanoid-good`]: https://github.com/y-gagar1n/nanoid-good nanoid-5.0.7/README.ru.md000066400000000000000000000444731460454646100147250ustar00rootroot00000000000000# Nano ID Логотип Nano ID от Антона Ловчикова [English](./README.md) | **Русский** | [简体中文](./README.zh-CN.md) | [Bahasa Indonesia](./README.id-ID.md) Генератор уникальных ID для JavaScript — лёгкий, безопасный, ID можно применять в URL. > «Поразительный уровень бессмысленного перфекционизма, > который просто невозможно не уважать» - **Лёгкий.** 116 байт (после минификации и Brotli). Без зависимостей. [Size Limit] следит за размером. - **Безопасный.** Использует аппаратный генератор случайных чисел. Можно использовать в кластерах машин. - **Короткие ID.** Используется больший алфавит, чем у UUID (`A-Za-z0-9_-`). Поэтому длина ID уменьшена с 36 до 21 символа. - **Работает везде.** Nano ID уже портировали на [20 языков программирования](#другие-языки-программирования). ```js import { nanoid } from 'nanoid' model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" ``` Поддерживает современные браузеры, IE ([с Babel]), Node.js и React Native. [online tool]: https://gitpod.io/#https://github.com/ai/nanoid/ [с babel]: https://developer.epages.com/blog/coding/how-to-transpile-node-modules-with-babel-and-webpack-in-a-monorepo/ [size limit]: https://github.com/ai/size-limit ---   Сделано в Злых марсианах, продуктовом консалитнге для инструментов разработки. --- ## Оглавление - [Сравнение с UUID](#сравнение-с-uuid) - [Сравнение производительности](#сравнение-производительности) - [Безопасность](#безопасность) - [Подключение](#подключение) - [API](#api) - [Блокирующий](#блокирующий) - [Небезопасный](#небезопасный) - [Смена алфавита или длины](#смена-алфавита-или-длины) - [Смена генератора случайных чисел](#смена-генератора-случайных-чисел) - [Руководство](#руководство) - [React](#react) - [React Native](#react-native) - [PouchDB и CouchDB](#pouchdb-и-couchdb) - [Веб-воркеры](#веб-воркеры) - [Терминал](#терминал) - [Другие языки программирования](#другие-языки-программирования) - [Инструменты](#инструменты) ## Сравнение с UUID Nano ID похож на UUID v4 (случайный). У них сравнимое число битов случайности в ID (126 у Nano ID против 122 у UUID), поэтому они обладают похожей вероятностью возникновения коллизий (повторной генерации ранее выданных ID): > Чтобы вероятность повтора приблизилась к 1 на миллиард, > нужно сгенерировать 103 триллиона ID. Но между ними есть 2 важных отличия: 1. Nano ID использует более широкий алфавит, и сравнимое количество битов случайности будут упакованы в более короткую строку (21 символ, против 36 у UUID). 2. Код Nano ID **в 4 раз меньше**, чем у `uuid/v4` — 130 байт против 423. ## Сравнение производительности ```rust $ node ./test/benchmark.js crypto.randomUUID 28,398,328 ops/sec uuid v4 10,254,199 ops/sec @napi-rs/uuid 15,110,625 ops/sec uid/secure 10,388,842 ops/sec @lukeed/uuid 8,914,507 ops/sec nanoid 7,484,029 ops/sec customAlphabet 4,867,017 ops/sec nanoid for browser 609,426 ops/sec secure-random-string 539,080 ops/sec uid-safe.sync 533,944 ops/sec shortid 59,609 ops/sec Non-secure: uid 95,579,977 ops/sec nanoid/non-secure 3,999,766 ops/sec rndm 3,981,914 ops/sec ``` Среда сравнения: Framework 13 7840U, Fedora 39, Node.js 21.6. ## Безопасность _См. также хорошую статью о теориях генераторов случайных чисел: [Secure random values (in Node.js)]_ - **Непредсказуемость.** Вместо предсказуемого `Math.random()`, Nano ID использует модуль `crypto` в Node.js и Web Crypto API в браузере. Эти модули дают доступ к аппаратному генератору случайных чисел. - **Равномерность.** Например, существует популярная ошибка `random % alphabet`, которую часто допускают при разработке генератора ID. Распределение вероятности для каждого символа может не быть одинаковым. Из-за неравномерности использования пространства алфавита, на перебор ID потребуется меньше времени, чем ожидается. Nano ID использует [более совершенный алгоритм], а равномерность распределения символов покрыта тестами. Распределение Nano ID - **Документация:** все хитрости Nano ID хорошо документированы — смотрите комментарии [в исходниках]. - **Уязвимости:** если вы нашли уязвимость в Nano ID, свяжитесь с [командой безопасности Tidelift](https://tidelift.com/security). Они проконтролируют исправление и проинформируют пользователей. [secure random values (in node.js)]: https://gist.github.com/joepie91/7105003c3b26e65efcea63f3db82dfba [более совершенный алгоритм]: https://github.com/ai/nanoid/blob/main/index.js [в исходниках]: https://github.com/ai/nanoid/blob/main/index.js ## Подключение ```bash npm install nanoid ``` Nano ID 5 работает только с ESM-проектами, в тестах или скриптах для Node.js. Для CommonJS вам нужен Nano ID 3.x (мы ещё всё ещё поддерживаем): ```bash npm install nanoid@3 ``` Для быстрого прототипирования вы можете подключить Nano ID с CDN без установки. Не используйте этот способ на реальном сайте, так как он сильно бьёт по скорости загрузки сайта. ```js import { nanoid } from 'https://cdn.jsdelivr.net/npm/nanoid/nanoid.js' ``` ## API Nano ID разделён на два модуля: стандартный и небезопасный. По умолчанию используются символы, безопасные для URL (`A-Za-z0-9_-`). Длина ID по умолчанию — 21 символ (чтобы вероятность коллизий была соизмеримой с UUID v4). ### Блокирующий Безопасный и простой в использовании способ использования Nano ID. Из-за особенностей работы генератора случайных чисел при использовании этого способа ЦПУ может иногда простаивать без работы. ```js import { nanoid } from 'nanoid' model.id = nanoid() //=> "V1StGXR8_Z5jdHi6B-myT" ``` Функция также принимает необязательный аргумент, задающий длину ID: ```js nanoid(10) //=> "IRFa-VaY2b" ``` При изменении размера, всегда проверяйте риски в нашем [калькуляторе коллизий](https://zelark.github.io/nano-id-cc/). ### Небезопасный По умолчанию, Nano ID использует аппаратный генератор случайных чисел для получения непредсказуемых ID и минимизации риска возникновения коллизий (повторной генерации ранее выданных ID). Но если вам не требуется устойчивость к подбору ID, то вы можете перейти на небезопасный генератор — это полезно там, где нет доступа к API аппаратного генератора случайных чисел. ```js import { nanoid } from 'nanoid/non-secure' const id = nanoid() //=> "Uakgb_J5m9g-0JDMbcJqLJ" ``` Но учтите, что предсказуемость ID может быть использована для атаки на систему. ### Смена алфавита или длины Функция `customAlphabet` позволяет создать свою функцию `nanoid` с нужным вам алфавитом и длиной ID. ```js import { customAlphabet } from 'nanoid' const nanoid = customAlphabet('1234567890abcdef', 10) user.id = nanoid() //=> "4f90d13a42" ``` ```js import { customAlphabet } from 'nanoid/non-secure' const nanoid = customAlphabet('1234567890abcdef', 10) user.id = nanoid() ``` Не забудьте проверить риски коллизии вашего алфавита и длины [на нашем калькуляторе]. [`nanoid-dictionary`] содержит много популярных примеров альтернативных алфавитов. Алфавит должен содержать ≤256 символов. Иначе мы не сможем гарантировать непредсказуемость ID. Длину ID можно менять не только в `customAlphabet()`, но и при вызове генератора, который она вернёт: ```js import { customAlphabet } from 'nanoid' const nanoid = customAlphabet('1234567890abcdef', 10) model.id = nanoid(5) //=> "f01a2" ``` [на нашем калькуляторе]: https://alex7kom.github.io/nano-nanoid-cc/ [`nanoid-dictionary`]: https://github.com/CyberAP/nanoid-dictionary ### Смена генератора случайных чисел Функция `customRandom` позволяет создать свою функцию `nanoid` со своими генераторами случайных чисел, алфавитом и длинной ID. Например, можно использовать генератор c seed для повторяемости тестов. ```js import { customRandom } from 'nanoid' const rng = seedrandom(seed) const nanoid = customRandom('abcdef', 10, size => { return new Uint8Array(size).map(() => 256 * rng()) }) nanoid() //=> "fbaefaadeb" ``` Функция в третьем аргументе `customRandom` должна принимать длину массива и возвращать нужный массив со случайными числами Если вы хотите заменить только генератор случайных чисел, но оставить URL-совместимый алфавит, то стандартный алфавит доступен в экспорте `urlAlphabet`. ```js const { customRandom, urlAlphabet } = require('nanoid') const nanoid = customRandom(urlAlphabet, 10, random) ``` ## Руководство ### React Не используйте Nano ID для генерации свойства `key` в JSX. При каждом рендере `key` будет разный, что плохо скажется на производительности. ```jsx function Todos({ todos }) { return (
      {todos.map(todo => (
    • /* НЕ ДЕЛАЙТЕ ТАК */ {todo.text}
    • ))}
    ) } ``` Для связи `` и `