From 4f5544255f3aba912c7662aca0434a4506953c5c Mon Sep 17 00:00:00 2001 From: Andrey Sitnik Date: Tue, 7 Jun 2022 10:16:23 +0200 Subject: [PATCH] Remove CJS support --- async/index.browser.js | 8 +-- async/index.js | 16 ++--- async/index.native.js | 12 ++-- bin/{nanoid.cjs => nanoid.js} | 2 +- index.browser.js | 11 ++-- index.js | 20 +++--- nanoid.js | 2 +- non-secure/index.js | 6 +- package.json | 19 ++++-- pnpm-lock.yaml | 53 +--------------- test/async.test.js | 99 ++++++------------------------ test/bin.test.js | 13 ++-- test/demo/index.js | 4 +- test/index.test.js | 10 +-- test/non-secure.test.js | 10 +-- test/react-native-polyfill.test.js | 8 +-- test/update-prebuild.js | 17 +++-- url-alphabet/index.js | 4 +- 18 files changed, 102 insertions(+), 212 deletions(-) rename bin/{nanoid.cjs => nanoid.js} (95%) diff --git a/async/index.browser.js b/async/index.browser.js index 402e2f4e..8e570030 100644 --- a/async/index.browser.js +++ b/async/index.browser.js @@ -1,6 +1,6 @@ -let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) +export let random = async bytes => crypto.getRandomValues(new Uint8Array(bytes)) -let customAlphabet = (alphabet, defaultSize = 21) => { +export let customAlphabet = (alphabet, defaultSize = 21) => { // 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. @@ -39,7 +39,7 @@ let customAlphabet = (alphabet, defaultSize = 21) => { } } -let nanoid = async (size = 21) => { +export let nanoid = async (size = 21) => { let id = '' let bytes = crypto.getRandomValues(new Uint8Array(size)) @@ -65,5 +65,3 @@ let nanoid = async (size = 21) => { } return id } - -module.exports = { nanoid, customAlphabet, random } diff --git a/async/index.js b/async/index.js index 1e634e91..0602637a 100644 --- a/async/index.js +++ b/async/index.js @@ -1,16 +1,17 @@ -let crypto = require('crypto') +import { randomFill } from 'crypto' -let { urlAlphabet } = require('../url-alphabet') +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 => +export 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) => { + randomFill(Buffer.allocUnsafe(bytes), (err, buf) => { if (err) { + /* c8 ignore next */ reject(err) } else { resolve(buf) @@ -18,7 +19,7 @@ let random = bytes => }) }) -let customAlphabet = (alphabet, defaultSize = 21) => { +export let customAlphabet = (alphabet, defaultSize = 21) => { // 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. @@ -47,13 +48,14 @@ let customAlphabet = (alphabet, defaultSize = 21) => { id += alphabet[bytes[i] & mask] || '' if (id.length === size) return id } + /* c8 ignore next */ return tick(id, size) }) return size => tick('', size) } -let nanoid = (size = 21) => +export let nanoid = (size = 21) => random(size).then(bytes => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. @@ -67,5 +69,3 @@ let nanoid = (size = 21) => } return id }) - -module.exports = { nanoid, customAlphabet, random } diff --git a/async/index.native.js b/async/index.native.js index 0ebdacd0..b2fbeb43 100644 --- a/async/index.native.js +++ b/async/index.native.js @@ -1,10 +1,10 @@ -let { getRandomBytesAsync } = require('expo-random') +import { getRandomBytesAsync } from 'expo-random' -let { urlAlphabet } = require('../url-alphabet') +import { urlAlphabet } from '../url-alphabet/index.js' -let random = getRandomBytesAsync +export let random = getRandomBytesAsync -let customAlphabet = (alphabet, defaultSize = 21) => { +export let customAlphabet = (alphabet, defaultSize = 21) => { // 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. @@ -39,7 +39,7 @@ let customAlphabet = (alphabet, defaultSize = 21) => { return size => tick('', size) } -let nanoid = (size = 21) => +export let nanoid = (size = 21) => random(size).then(bytes => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. @@ -53,5 +53,3 @@ let nanoid = (size = 21) => } return id }) - -module.exports = { nanoid, customAlphabet, random } diff --git a/bin/nanoid.cjs b/bin/nanoid.js similarity index 95% rename from bin/nanoid.cjs rename to bin/nanoid.js index c76db0fa..e9a39928 100755 --- a/bin/nanoid.cjs +++ b/bin/nanoid.js @@ -1,6 +1,6 @@ #!/usr/bin/env node -let { nanoid, customAlphabet } = require('..') +import { nanoid, customAlphabet } from '../index.js' function print(msg) { process.stdout.write(msg + '\n') diff --git a/index.browser.js b/index.browser.js index 7ab1562c..090a1a90 100644 --- a/index.browser.js +++ b/index.browser.js @@ -1,11 +1,11 @@ // This file replaces `index.js` in bundlers like webpack or Rollup, // according to `browser` config in `package.json`. -let { urlAlphabet } = require('./url-alphabet') +export { urlAlphabet } from './url-alphabet/index.js' -let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) +export let random = bytes => crypto.getRandomValues(new Uint8Array(bytes)) -let customRandom = (alphabet, defaultSize, getRandom) => { +export let customRandom = (alphabet, defaultSize, 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. @@ -44,10 +44,10 @@ let customRandom = (alphabet, defaultSize, getRandom) => { } } -let customAlphabet = (alphabet, size = 21) => +export let customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size, random) -let nanoid = (size = 21) => +export let nanoid = (size = 21) => crypto.getRandomValues(new Uint8Array(size)).reduce((id, byte) => { // It is incorrect to use bytes exceeding the alphabet size. // The following mask reduces the random byte in the 0-255 value @@ -69,4 +69,3 @@ let nanoid = (size = 21) => return id }, '') -module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/index.js b/index.js index 977f07b0..a7f828a3 100644 --- a/index.js +++ b/index.js @@ -1,6 +1,8 @@ -let crypto = require('crypto') +import { randomFillSync } from 'crypto' -let { urlAlphabet } = require('./url-alphabet') +import { urlAlphabet } from './url-alphabet/index.js' + +export { urlAlphabet } // It is best to make fewer, larger requests to the crypto module to // avoid system call overhead. So, random numbers are generated in a @@ -13,22 +15,22 @@ let pool, poolOffset let fillPool = bytes => { if (!pool || pool.length < bytes) { pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER) - crypto.randomFillSync(pool) + randomFillSync(pool) poolOffset = 0 } else if (poolOffset + bytes > pool.length) { - crypto.randomFillSync(pool) + randomFillSync(pool) poolOffset = 0 } poolOffset += bytes } -let random = bytes => { +export let random = bytes => { // `-=` convert `bytes` to number to prevent `valueOf` abusing fillPool((bytes -= 0)) return pool.subarray(poolOffset - bytes, poolOffset) } -let customRandom = (alphabet, defaultSize, getRandom) => { +export let customRandom = (alphabet, defaultSize, 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. @@ -63,10 +65,10 @@ let customRandom = (alphabet, defaultSize, getRandom) => { } } -let customAlphabet = (alphabet, size = 21) => +export let customAlphabet = (alphabet, size = 21) => customRandom(alphabet, size, random) -let nanoid = (size = 21) => { +export let nanoid = (size = 21) => { // `-=` convert `size` to number to prevent `valueOf` abusing fillPool((size -= 0)) let id = '' @@ -81,5 +83,3 @@ let nanoid = (size = 21) => { } return id } - -module.exports = { nanoid, customAlphabet, customRandom, urlAlphabet, random } diff --git a/nanoid.js b/nanoid.js index ec242ead..493f9a2c 100644 --- a/nanoid.js +++ b/nanoid.js @@ -1 +1 @@ -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?"_":"-"),""); \ No newline at end of file +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>62?"-":"_"),""); \ No newline at end of file diff --git a/non-secure/index.js b/non-secure/index.js index 947d84fa..78e522fa 100644 --- a/non-secure/index.js +++ b/non-secure/index.js @@ -7,7 +7,7 @@ let urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' -let customAlphabet = (alphabet, defaultSize = 21) => { +export let customAlphabet = (alphabet, defaultSize = 21) => { return (size = defaultSize) => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. @@ -20,7 +20,7 @@ let customAlphabet = (alphabet, defaultSize = 21) => { } } -let nanoid = (size = 21) => { +export let nanoid = (size = 21) => { let id = '' // A compact alternative for `for (var i = 0; i < step; i++)`. let i = size @@ -30,5 +30,3 @@ let nanoid = (size = 21) => { } return id } - -module.exports = { nanoid, customAlphabet } diff --git a/package.json b/package.json index 8b9df6b5..96249fdf 100644 --- a/package.json +++ b/package.json @@ -14,12 +14,25 @@ "test": "c8 pnpm unit && eslint . && pnpm clean && size-limit", "start": "vite test/demo/ --open" }, + "type": "module", "engines": { "node": "^14 || ^16 || >=18" }, "author": "Andrey Sitnik ", "license": "MIT", "repository": "ai/nanoid", + "exports": { + ".": { + "browser": "./index.browser.js", + "default": "./index.js" + }, + "./async": { + "browser": "./async/index.browser.js", + "default": "./async/index.js" + }, + "./non-secure": "./non-secure/index.js", + "./package.json": "./package.json" + }, "browser": { "./index.js": "./index.browser.js", "./async/index.js": "./async/index.browser.js", @@ -28,7 +41,7 @@ "react-native": { "./async/index.js": "./async/index.native.js" }, - "bin": "./bin/nanoid.cjs", + "bin": "./bin/nanoid.js", "sideEffects": false, "types": "./index.d.ts", "devDependencies": { @@ -37,21 +50,19 @@ "@lukeed/uuid": "^2.0.0", "@napi-rs/uuid": "^0.2.1", "@originjs/vite-plugin-commonjs": "^1.0.3", - "@size-limit/dual-publish": "^7.0.8", "@size-limit/file": "^7.0.8", "@size-limit/webpack": "^7.0.8", "@types/node": "^17.0.40", "benchmark": "^2.1.4", "c8": "^7.11.3", + "clean-publish": "^4.0.0", "cuid": "^2.1.8", - "dual-publish": "^3.0.1", "eslint": "^8.17.0", "eslint-config-standard": "^17.0.0", "eslint-plugin-import": "^2.26.0", "eslint-plugin-n": "^15.2.1", "eslint-plugin-prefer-let": "^3.0.1", "eslint-plugin-promise": "^6.0.0", - "nanospy": "^0.5.0", "picocolors": "^1.0.0", "postcss": "^8.4.14", "rndm": "^1.2.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index a3a2a5fd..d48c252f 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -6,21 +6,19 @@ specifiers: '@lukeed/uuid': ^2.0.0 '@napi-rs/uuid': ^0.2.1 '@originjs/vite-plugin-commonjs': ^1.0.3 - '@size-limit/dual-publish': ^7.0.8 '@size-limit/file': ^7.0.8 '@size-limit/webpack': ^7.0.8 '@types/node': ^17.0.40 benchmark: ^2.1.4 c8: ^7.11.3 + clean-publish: ^4.0.0 cuid: ^2.1.8 - dual-publish: ^3.0.1 eslint: ^8.17.0 eslint-config-standard: ^17.0.0 eslint-plugin-import: ^2.26.0 eslint-plugin-n: ^15.2.1 eslint-plugin-prefer-let: ^3.0.1 eslint-plugin-promise: ^6.0.0 - nanospy: ^0.5.0 picocolors: ^1.0.0 postcss: ^8.4.14 rndm: ^1.2.0 @@ -40,21 +38,19 @@ devDependencies: '@lukeed/uuid': 2.0.0 '@napi-rs/uuid': 0.2.1 '@originjs/vite-plugin-commonjs': 1.0.3 - '@size-limit/dual-publish': 7.0.8_wqfv2ceb3uqygah5qee4bz7v2e '@size-limit/file': 7.0.8_size-limit@7.0.8 '@size-limit/webpack': 7.0.8_size-limit@7.0.8 '@types/node': 17.0.40 benchmark: 2.1.4 c8: 7.11.3 + clean-publish: 4.0.0 cuid: 2.1.8 - dual-publish: 3.0.1 eslint: 8.17.0 eslint-config-standard: 17.0.0_k2gkawvnhbuxb7ddaipaawnv5q eslint-plugin-import: 2.26.0_eslint@8.17.0 eslint-plugin-n: 15.2.1_eslint@8.17.0 eslint-plugin-prefer-let: 3.0.1 eslint-plugin-promise: 6.0.0_eslint@8.17.0 - nanospy: 0.5.0 picocolors: 1.0.0 postcss: 8.4.14 rndm: 1.2.0 @@ -535,17 +531,6 @@ packages: esbuild: 0.14.42 dev: true - /@size-limit/dual-publish/7.0.8_wqfv2ceb3uqygah5qee4bz7v2e: - resolution: {integrity: sha512-TiupMMHp4Lm7TwATJ4k5tErQ38qdX2+7F4yo1FqpHEYaYKo2qj1FtNi1Smn066faIUNJ6iVDZ2V9hM64eTsLig==} - engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} - peerDependencies: - dual-publish: '> 0.6.0' - size-limit: 7.0.8 - dependencies: - dual-publish: 3.0.1 - size-limit: 7.0.8 - dev: true - /@size-limit/file/7.0.8_size-limit@7.0.8: resolution: {integrity: sha512-1KeFQuMXIXAH/iELqIX7x+YNYDFvzIvmxcp9PrdwEoSNL0dXdaDIo9WE/yz8xvOmUcKaLfqbWkL75DM0k91WHQ==} engines: {node: ^12.0.0 || ^14.0.0 || >=16.0.0} @@ -1093,17 +1078,6 @@ packages: esutils: 2.0.3 dev: true - /dual-publish/3.0.1: - resolution: {integrity: sha512-nVBrd2y9/jlyeG6OD2U/F1BrFFCL5zkBPDBHsTbWTRYqfartbEOR8pQImEFh44PRQfX4PtOrOM5Uatv7f6i1Tg==} - engines: {node: '>=16.0.0'} - hasBin: true - dependencies: - clean-publish: 4.0.0 - fast-glob: 3.2.11 - line-column: 1.0.2 - picocolors: 1.0.0 - dev: true - /electron-to-chromium/1.4.147: resolution: {integrity: sha512-czclPqxLMPqPMkahKcske4TaS5lcznsc26ByBlEFDU8grTBVK9C5W6K9I6oEEhm4Ai4jTihGnys90xY1yjXcRg==} dev: true @@ -2031,21 +2005,10 @@ packages: call-bind: 1.0.2 dev: true - /isarray/1.0.0: - resolution: {integrity: sha512-VLghIWNM6ELQzo7zwmcg0NmTVyWKYjvIeM83yjp0wRDTmUnrM678fQbcKBo6n2CJEF0szoG//ytg+TKla89ALQ==} - dev: true - /isexe/2.0.0: resolution: {integrity: sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw==} dev: true - /isobject/2.1.0: - resolution: {integrity: sha512-+OUdGJlgjOBZDfxnDjYYG6zp487z0JGNQq3cYQYg5f5hKR+syHMsaztzGeml/4kGG55CSpKSpWTY+jYGgsHLgA==} - engines: {node: '>=0.10.0'} - dependencies: - isarray: 1.0.0 - dev: true - /istanbul-lib-coverage/3.2.0: resolution: {integrity: sha512-eOeJ5BHCmHYvQK7xt9GkdHuzuCGS1Y6g9Gvnx3Ym33fz/HpLRYxiS0wHNr+m/MBC8B647Xt608vCDEvhl9c6Mw==} engines: {node: '>=8'} @@ -2137,13 +2100,6 @@ packages: engines: {node: '>=10'} dev: true - /line-column/1.0.2: - resolution: {integrity: sha512-Ktrjk5noGYlHsVnYWh62FLVs4hTb8A3e+vucNZMgPeAOITdshMSgv4cCZQeRDjm7+goqmo6+liZwTXo+U3sVww==} - dependencies: - isarray: 1.0.0 - isobject: 2.1.0 - dev: true - /loader-runner/4.3.0: resolution: {integrity: sha512-3R/1M+yS3j5ou80Me59j7F9IMs4PXs3VqRrm0TU3AbKPxlmpoY1TNscJV/oGJXo8qCatFGTfDbY6W6ipGOYXfg==} engines: {node: '>=6.11.5'} @@ -2264,11 +2220,6 @@ packages: picocolors: 1.0.0 dev: true - /nanospy/0.5.0: - resolution: {integrity: sha512-QxH93ntkjRiSP+gJrBLcgOO3neU6pGhUKjPAJ7rAFag/+tJ+/0lw6dXic+iXUQ/3Cxk4Dp/FwLnf57xnQsjecQ==} - engines: {node: ^8.0.0 || ^10.0.0 || ^12.0.0 || ^14.0.0 || >=16.0.0} - dev: true - /natural-compare/1.4.0: resolution: {integrity: sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw==} dev: true diff --git a/test/async.test.js b/test/async.test.js index 1ffd789a..ecaa141b 100644 --- a/test/async.test.js +++ b/test/async.test.js @@ -1,7 +1,9 @@ -let { suite } = require('uvu') -let { spy } = require('nanospy') -let { is, match, ok } = require('uvu/assert') -let crypto = require('crypto') +import { is, match, ok } from 'uvu/assert' +import { test } from 'uvu' + +import { urlAlphabet } from '../index.js' +import * as browser from '../async/index.browser.js' +import * as node from '../async/index.js' global.crypto = { getRandomValues(array) { @@ -12,10 +14,6 @@ global.crypto = { } } -let { urlAlphabet } = require('..') -let browser = require('../async/index.browser.js') -let node = require('../async/index.js') - function times(size, callback) { let array = [] for (let i = 0; i < size; i++) { @@ -27,40 +25,25 @@ function times(size, callback) { for (let type of ['node', 'browser']) { let { nanoid, customAlphabet, random } = type === 'node' ? node : browser - function mock(callback) { - crypto.randomFill = callback - delete require.cache[require.resolve('../async')] - nanoid = require('../async').nanoid - } - - let nanoidSuite = suite(`${type} / nanoid`) - - if (type === 'node') { - let originFill = crypto.randomFill - nanoidSuite.after.each(() => { - mock(originFill) - }) - } - - nanoidSuite('generates URL-friendly IDs', async () => { + test(`${type} / nanoid / generates URL-friendly IDs`, async () => { await Promise.all( times(100, async () => { let id = await nanoid() is(id.length, 21) is(typeof id, 'string') for (let char of id) { - match(urlAlphabet, new RegExp(char, "g")) + match(urlAlphabet, new RegExp(char, 'g')) } }) ) }) - nanoidSuite('changes ID length', async () => { + test(`${type} / nanoid / changes ID length`, async () => { let id = await nanoid(10) is(id.length, 10) }) - nanoidSuite('has no collisions', async () => { + test(`${type} / nanoid / has no collisions`, async () => { let ids = await Promise.all(times(50 * 1000, () => nanoid())) ids.reduce((used, id) => { is(used[id], undefined) @@ -69,7 +52,7 @@ for (let type of ['node', 'browser']) { }, []) }) - nanoidSuite('has flat distribution', async () => { + test(`${type} / nanoid / has flat distribution`, async () => { let COUNT = 100 * 1000 let LENGTH = (await nanoid()).length @@ -94,31 +77,11 @@ for (let type of ['node', 'browser']) { ok(max - min <= 0.05) }) - if (type === 'node') { - nanoidSuite('rejects Promise on error', async () => { - let error = new Error('test') - mock((buffer, callback) => { - callback(error) - }) - let catched - try { - await nanoid() - } catch (e) { - catched = e - } - is(catched, error) - }) - } - - nanoidSuite.run() - - let randomSuite = suite(`${type} / random`) - - randomSuite('generates small random buffers', async () => { + test(`${type} / random / generates small random buffers`, async () => { is((await random(10)).length, 10) }) - randomSuite('generates random buffers', async () => { + test(`${type} / random / generates random buffers`, async () => { let numbers = {} let bytes = await random(10000) is(bytes.length, 10000) @@ -131,24 +94,13 @@ for (let type of ['node', 'browser']) { } }) - randomSuite.run() - - let customAlphabetSuite = suite(`${type} / customAlphabet`) - - if (type === 'node') { - let originFill = crypto.randomFill - customAlphabetSuite.after.each(() => { - mock(originFill) - }) - } - - customAlphabetSuite('has options', async () => { + test(`${type} / customAlphabet / has options`, async () => { let nanoidA = customAlphabet('a', 5) let id = await nanoidA() is(id, 'aaaaa') }) - customAlphabetSuite('has flat distribution', async () => { + test(`${type} / customAlphabet / has flat distribution`, async () => { let COUNT = 50 * 1000 let LENGTH = 30 let ALPHABET = 'abcdefghijklmnopqrstuvwxy' @@ -176,26 +128,11 @@ for (let type of ['node', 'browser']) { ok(max - min <= 0.05) }) - customAlphabetSuite('changes size', async () => { + test(`${type} / customAlphabet / changes size`, async () => { let nanoidA = customAlphabet('a') let id = await nanoidA(10) is(id, 'aaaaaaaaaa') }) - - if (type === 'node') { - customAlphabetSuite('should call random two times', async () => { - let randomFillMock = spy((buffer, callback) => - callback(null, [220, 215, 129, 35, 242, 202, 137, 180]) - ) - mock(randomFillMock) - - let nanoidA = customAlphabet('a', 5) - let id = await nanoidA() - - is(randomFillMock.callCount, 2) - is(id, 'aaaaa') - }) - } - - customAlphabetSuite.run() } + +test.run() diff --git a/test/bin.test.js b/test/bin.test.js index 91e96c53..ff421107 100644 --- a/test/bin.test.js +++ b/test/bin.test.js @@ -1,12 +1,13 @@ -let { is, match } = require('uvu/assert') -let { promisify } = require('util') -let { test } = require('uvu') -let { join } = require('path') -let child = require('child_process') +import { fileURLToPath } from 'url' +import { is, match } from 'uvu/assert' +import { promisify } from 'util' +import { test } from 'uvu' +import { join } from 'path' +import child from 'child_process' let exec = promisify(child.exec) -const BIN = join(__dirname, '..', 'bin', 'nanoid.cjs') +const BIN = join(fileURLToPath(import.meta.url), '..', '..', 'bin', 'nanoid.js') test('prints unique ID', async () => { let { stdout, stderr } = await exec('node ' + BIN) diff --git a/test/demo/index.js b/test/demo/index.js index 406f4384..1624444d 100644 --- a/test/demo/index.js +++ b/test/demo/index.js @@ -1,8 +1,8 @@ import { v4 as uuid4 } from 'uuid' import shortid from 'shortid' -import nanoidExport from '../../index.browser.js' -import nonSecureExport from '../../non-secure/index.js' +import * as nanoidExport from '../../index.browser.js' +import * as nonSecureExport from '../../non-secure/index.js' let { nanoid, customAlphabet, random } = nanoidExport let nonSecure = nonSecureExport.nanoid diff --git a/test/index.test.js b/test/index.test.js index 9bc3350c..ce0ec1ce 100644 --- a/test/index.test.js +++ b/test/index.test.js @@ -1,8 +1,8 @@ -let { test } = require('uvu') -let { is, ok, equal, match } = require('uvu/assert') +import { is, ok, equal, match } from 'uvu/assert' +import { test } from 'uvu' -let browser = require('../index.browser.js') -let node = require('../index.js') +import * as browser from '../index.browser.js' +import * as node from '../index.js' test.before(() => { global.crypto = { @@ -29,7 +29,7 @@ for (let type of ['node', 'browser']) { is(id.length, 21) is(typeof id, 'string') for (let char of id) { - match(urlAlphabet, new RegExp(char, "g")) + match(urlAlphabet, new RegExp(char, 'g')) } } }) diff --git a/test/non-secure.test.js b/test/non-secure.test.js index 6b6117b4..77fa1058 100644 --- a/test/non-secure.test.js +++ b/test/non-secure.test.js @@ -1,15 +1,15 @@ -let { test } = require('uvu') -let { is, match, ok } = require('uvu/assert') +import { is, match, ok } from 'uvu/assert' +import { test } from 'uvu' -let { nanoid, customAlphabet } = require('../non-secure') -let { urlAlphabet } = require('..') +import { nanoid, customAlphabet } from '../non-secure/index.js' +import { urlAlphabet } from '../index.js' test('nanoid / generates URL-friendly IDs', () => { for (let i = 0; i < 10; i++) { let id = nanoid() is(id.length, 21) for (let char of id) { - match(urlAlphabet, new RegExp(char, "g")) + match(urlAlphabet, new RegExp(char, 'g')) } } }) diff --git a/test/react-native-polyfill.test.js b/test/react-native-polyfill.test.js index d6615ed7..7dd730ab 100644 --- a/test/react-native-polyfill.test.js +++ b/test/react-native-polyfill.test.js @@ -1,5 +1,7 @@ -let { test } = require('uvu') -let { is } = require('uvu/assert') +import { test } from 'uvu' +import { is } from 'uvu/assert' + +import { nanoid } from '../index.browser.js' test.before(() => { global.navigator = { @@ -22,8 +24,6 @@ test.after(() => { }) test('works with polyfill', () => { - let { nanoid } = require('../index.browser') - is(typeof nanoid(), 'string') }) diff --git a/test/update-prebuild.js b/test/update-prebuild.js index 548b6762..c6291963 100755 --- a/test/update-prebuild.js +++ b/test/update-prebuild.js @@ -1,18 +1,17 @@ #!/usr/bin/env node -let { promisify } = require('util') -let { minify } = require('terser') -let { join } = require('path') -let fs = require('fs') +import { readFile, writeFile } from 'fs/promises' +import { fileURLToPath } from 'url' +import { minify } from 'terser' +import { join } from 'path' -let writeFile = promisify(fs.writeFile) -let readFile = promisify(fs.readFile) +const ROOT = join(fileURLToPath(import.meta.url), '..', '..') async function build() { - let js = await readFile(join(__dirname, '..', 'index.browser.js')) - let func = 'export ' + js.toString().match(/(let nanoid [\W\w]*)\s*module/)[1] + let js = await readFile(join(ROOT, 'index.browser.js')) + let func = js.toString().match(/(export let nanoid [\W\w]*$)/)[1] let { code } = await minify(func) - await writeFile(join(__dirname, '..', 'nanoid.js'), code) + await writeFile(join(ROOT, 'nanoid.js'), code) } build().catch(e => { diff --git a/url-alphabet/index.js b/url-alphabet/index.js index a332f0bf..fc64667f 100644 --- a/url-alphabet/index.js +++ b/url-alphabet/index.js @@ -1,7 +1,5 @@ // This alphabet uses `A-Za-z0-9_-` symbols. // The order of characters is optimized for better gzip and brotli compression. // Same as in non-secure/index.js -let urlAlphabet = +export const urlAlphabet = 'useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict' - -module.exports = { urlAlphabet }