JS Standard. Some fixes with the test. Better structure

This commit is contained in:
juanelas 2020-04-06 13:17:22 +02:00
parent 685bd1a538
commit c29b520108
10605 changed files with 1840285 additions and 5077 deletions

View File

@ -1,36 +0,0 @@
{
"env": {
"node": true,
"browser": true,
"mocha": true,
"worker": true
},
"parserOptions": {
"ecmaVersion": 2017,
"sourceType": "module"
},
"extends": "eslint:recommended",
"rules": {
"no-console": 0,
"indent": [
"error",
4
],
"linebreak-style": [
"error",
"unix"
],
"quotes": [
"error",
"single"
],
"semi": [
"error",
"always"
]
},
"globals": {
"BigInt": "readonly",
"Uint8Array": "readonly"
}
}

19
.gitignore vendored
View File

@ -1,19 +0,0 @@
# Project specific files
dist/bigint-crypto-utils-?.?.?.*
# Logs
logs
*.log
npm-debug.log*
# Dependency directories
node_modules/
# Output of 'npm pack'
*.tgz
# Visual Studio Code
.vscode
# IntelliJ
.idea/

View File

@ -1,6 +1,3 @@
# Project specific files
dist/bigint-crypto-utils-?.?.?.*
# Build scripts
build/*
@ -10,7 +7,6 @@ src/*
# Test files
test/*
# Logs
logs
*.log
@ -21,6 +17,3 @@ npm-debug.log*
# Visual Studio Code
.vscode
# EsLint Config
.eslintrc.json

View File

@ -1,3 +1,5 @@
[![JavaScript Style Guide](https://img.shields.io/badge/code_style-standard-brightgreen.svg)](https://standardjs.com)
# bigint-crypto-utils
Utils for working with cryptography using native JS ([ES-2020](https://tc39.es/ecma262/#sec-bigint-objects)) implementation of BigInt. It includes some extra functions to work with modular arithmetics along with secure random numbers and a fast strong probable prime generator/tester (parallelised multi-threaded Miller-Rabin primality test). It can be used by any [Web Browser or webview supporting BigInt](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt#Browser_compatibility) and with Node.js (>=10.4.0). In the latter case, for multi-threaded primality tests, you should use Node.js v11 or newer or enable at runtime with `node --experimental-worker` with Node.js version >= 10.5.0 and < 11.
@ -89,9 +91,9 @@ You can just load the module in a html page as:
BigInt is [ES-2020](https://tc39.es/ecma262/#sec-bigint-objects). In order to use it with TypeScript you should set `lib` (and probably also `target` and `module`) to `esnext` in `tsconfig.json`.
# bigint-crypto-utils JS Doc
## bigint-crypto-utils JS Doc
## Functions
### Functions
<dl>
<dt><a href="#abs">abs(a)</a><code>bigint</code></dt>
@ -101,14 +103,14 @@ BigInt is [ES-2020](https://tc39.es/ecma262/#sec-bigint-objects). In order to us
<dd><p>Returns the bitlength of a number</p>
</dd>
<dt><a href="#eGcd">eGcd(a, b)</a><code><a href="#egcdReturn">egcdReturn</a></code></dt>
<dd><p>An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
<dd><p>An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
Take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).</p>
</dd>
<dt><a href="#gcd">gcd(a, b)</a><code>bigint</code></dt>
<dd><p>Greatest-common divisor of two integers based on the iterative binary algorithm.</p>
</dd>
<dt><a href="#isProbablyPrime">isProbablyPrime(w, [iterations])</a><code>Promise.&lt;boolean&gt;</code></dt>
<dd><p>The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
<dt><a href="#isProbablyPrime">isProbablyPrime(w, [iterations])</a><code>Promise</code></dt>
<dd><p>The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)</p>
</dd>
<dt><a href="#lcm">lcm(a, b)</a><code>bigint</code></dt>
@ -126,15 +128,15 @@ iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)</p>
<dt><a href="#modPow">modPow(b, e, n)</a><code>bigint</code></dt>
<dd><p>Modular exponentiation b**e mod n. Currently using the right-to-left binary method</p>
</dd>
<dt><a href="#prime">prime(bitLength, [iterations])</a><code>Promise.&lt;bigint&gt;</code></dt>
<dd><p>A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
main process, and it can be much faster (if several cores or cpu are available).
The node version can also use worker_threads if they are available (enabled by default with Node 11 and
<dt><a href="#prime">prime(bitLength, [iterations])</a><code>Promise</code></dt>
<dd><p>A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
main process, and it can be much faster (if several cores or cpu are available).
The node version can also use worker_threads if they are available (enabled by default with Node 11 and
and can be enabled at runtime executing node --experimental-worker with node &gt;=10.5.0).</p>
</dd>
<dt><a href="#primeSync">primeSync(bitLength, [iterations])</a><code>bigint</code></dt>
<dd><p>A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
<dd><p>A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
The sync version is NOT RECOMMENDED since it won&#39;t use workers and thus it&#39;ll be slower and may freeze thw window in browser&#39;s javascript. Please consider using prime() instead.</p>
</dd>
<dt><a href="#randBetween">randBetween(max, [min])</a><code>bigint</code></dt>
@ -143,7 +145,7 @@ The sync version is NOT RECOMMENDED since it won&#39;t use workers and thus it&#
<dt><a href="#randBits">randBits(bitLength, [forceLength])</a><code>Buffer</code> | <code>Uint8Array</code></dt>
<dd><p>Secure random bits for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()</p>
</dd>
<dt><a href="#randBytes">randBytes(byteLength, [forceLength])</a><code>Promise.&lt;(Buffer|Uint8Array)&gt;</code></dt>
<dt><a href="#randBytes">randBytes(byteLength, [forceLength])</a><code>Promise</code></dt>
<dd><p>Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()</p>
</dd>
<dt><a href="#randBytesSync">randBytesSync(byteLength, [forceLength])</a><code>Buffer</code> | <code>Uint8Array</code></dt>
@ -154,7 +156,7 @@ The sync version is NOT RECOMMENDED since it won&#39;t use workers and thus it&#
</dd>
</dl>
## Typedefs
### Typedefs
<dl>
<dt><a href="#egcdReturn">egcdReturn</a> : <code>Object</code></dt>
@ -164,7 +166,7 @@ The sync version is NOT RECOMMENDED since it won&#39;t use workers and thus it&#
<a name="abs"></a>
## abs(a) ⇒ <code>bigint</code>
### abs(a) ⇒ <code>bigint</code>
Absolute value. abs(a)==a if a>=0. abs(a)==-a if a<0
**Kind**: global function
@ -176,7 +178,7 @@ Absolute value. abs(a)==a if a>=0. abs(a)==-a if a<0
<a name="bitLength"></a>
## bitLength(a) ⇒ <code>number</code>
### bitLength(a) ⇒ <code>number</code>
Returns the bitlength of a number
**Kind**: global function
@ -188,8 +190,8 @@ Returns the bitlength of a number
<a name="eGcd"></a>
## eGcd(a, b) ⇒ [<code>egcdReturn</code>](#egcdReturn)
An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
### eGcd(a, b) ⇒ [<code>egcdReturn</code>](#egcdReturn)
An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
Take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).
**Kind**: global function
@ -202,7 +204,7 @@ Take positive integers a, b as input, and return a triple (g, x, y), such that a
<a name="gcd"></a>
## gcd(a, b) ⇒ <code>bigint</code>
### gcd(a, b) ⇒ <code>bigint</code>
Greatest-common divisor of two integers based on the iterative binary algorithm.
**Kind**: global function
@ -215,12 +217,12 @@ Greatest-common divisor of two integers based on the iterative binary algorithm.
<a name="isProbablyPrime"></a>
## isProbablyPrime(w, [iterations]) ⇒ <code>Promise.&lt;boolean&gt;</code>
The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
### isProbablyPrime(w, [iterations]) ⇒ <code>Promise</code>
The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)
**Kind**: global function
**Returns**: <code>Promise.&lt;boolean&gt;</code> - A promise that resolves to a boolean that is either true (a probably prime number) or false (definitely composite)
**Returns**: <code>Promise</code> - A promise that resolves to a boolean that is either true (a probably prime number) or false (definitely composite)
| Param | Type | Default | Description |
| --- | --- | --- | --- |
@ -229,7 +231,7 @@ iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)
<a name="lcm"></a>
## lcm(a, b) ⇒ <code>bigint</code>
### lcm(a, b) ⇒ <code>bigint</code>
The least common multiple computed as abs(a*b)/gcd(a,b)
**Kind**: global function
@ -242,7 +244,7 @@ The least common multiple computed as abs(a*b)/gcd(a,b)
<a name="max"></a>
## max(a, b) ⇒ <code>bigint</code>
### max(a, b) ⇒ <code>bigint</code>
Maximum. max(a,b)==a if a>=b. max(a,b)==b if a<=b
**Kind**: global function
@ -255,7 +257,7 @@ Maximum. max(a,b)==a if a>=b. max(a,b)==b if a<=b
<a name="min"></a>
## min(a, b) ⇒ <code>bigint</code>
### min(a, b) ⇒ <code>bigint</code>
Minimum. min(a,b)==b if a>=b. min(a,b)==a if a<=b
**Kind**: global function
@ -268,7 +270,7 @@ Minimum. min(a,b)==b if a>=b. min(a,b)==a if a<=b
<a name="modInv"></a>
## modInv(a, n) ⇒ <code>bigint</code>
### modInv(a, n) ⇒ <code>bigint</code>
Modular inverse.
**Kind**: global function
@ -281,7 +283,7 @@ Modular inverse.
<a name="modPow"></a>
## modPow(b, e, n) ⇒ <code>bigint</code>
### modPow(b, e, n) ⇒ <code>bigint</code>
Modular exponentiation b**e mod n. Currently using the right-to-left binary method
**Kind**: global function
@ -295,15 +297,15 @@ Modular exponentiation b**e mod n. Currently using the right-to-left binary meth
<a name="prime"></a>
## prime(bitLength, [iterations]) ⇒ <code>Promise.&lt;bigint&gt;</code>
A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
main process, and it can be much faster (if several cores or cpu are available).
The node version can also use worker_threads if they are available (enabled by default with Node 11 and
### prime(bitLength, [iterations]) ⇒ <code>Promise</code>
A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
main process, and it can be much faster (if several cores or cpu are available).
The node version can also use worker_threads if they are available (enabled by default with Node 11 and
and can be enabled at runtime executing node --experimental-worker with node >=10.5.0).
**Kind**: global function
**Returns**: <code>Promise.&lt;bigint&gt;</code> - A promise that resolves to a bigint probable prime of bitLength bits.
**Returns**: <code>Promise</code> - A promise that resolves to a bigint probable prime of bitLength bits.
| Param | Type | Default | Description |
| --- | --- | --- | --- |
@ -312,8 +314,8 @@ and can be enabled at runtime executing node --experimental-worker with node >=1
<a name="primeSync"></a>
## primeSync(bitLength, [iterations]) ⇒ <code>bigint</code>
A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
### primeSync(bitLength, [iterations]) ⇒ <code>bigint</code>
A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
The sync version is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript. Please consider using prime() instead.
**Kind**: global function
@ -326,7 +328,7 @@ The sync version is NOT RECOMMENDED since it won't use workers and thus it'll be
<a name="randBetween"></a>
## randBetween(max, [min]) ⇒ <code>bigint</code>
### randBetween(max, [min]) ⇒ <code>bigint</code>
Returns a cryptographically secure random integer between [min,max]
**Kind**: global function
@ -339,7 +341,7 @@ Returns a cryptographically secure random integer between [min,max]
<a name="randBits"></a>
## randBits(bitLength, [forceLength]) ⇒ <code>Buffer</code> \| <code>Uint8Array</code>
### randBits(bitLength, [forceLength]) ⇒ <code>Buffer</code> \| <code>Uint8Array</code>
Secure random bits for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
**Kind**: global function
@ -352,11 +354,11 @@ Secure random bits for both node and browsers. Node version uses crypto.randomFi
<a name="randBytes"></a>
## randBytes(byteLength, [forceLength]) ⇒ <code>Promise.&lt;(Buffer\|Uint8Array)&gt;</code>
### randBytes(byteLength, [forceLength]) ⇒ <code>Promise</code>
Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
**Kind**: global function
**Returns**: <code>Promise.&lt;(Buffer\|Uint8Array)&gt;</code> - A promise that resolves to a Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
**Returns**: <code>Promise</code> - A promise that resolves to a Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
| Param | Type | Default | Description |
| --- | --- | --- | --- |
@ -365,7 +367,7 @@ Secure random bytes for both node and browsers. Node version uses crypto.randomF
<a name="randBytesSync"></a>
## randBytesSync(byteLength, [forceLength]) ⇒ <code>Buffer</code> \| <code>Uint8Array</code>
### randBytesSync(byteLength, [forceLength]) ⇒ <code>Buffer</code> \| <code>Uint8Array</code>
Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
**Kind**: global function
@ -378,7 +380,7 @@ Secure random bytes for both node and browsers. Node version uses crypto.randomF
<a name="toZn"></a>
## toZn(a, n) ⇒ <code>bigint</code>
### toZn(a, n) ⇒ <code>bigint</code>
Finds the smallest positive element that is congruent to a in modulo n
**Kind**: global function
@ -391,7 +393,7 @@ Finds the smallest positive element that is congruent to a in modulo n
<a name="egcdReturn"></a>
## egcdReturn : <code>Object</code>
### egcdReturn : <code>Object</code>
A triple (g, x, y), such that ax + by = g = gcd(a, b).
**Kind**: global typedef
@ -403,5 +405,3 @@ A triple (g, x, y), such that ax + by = g = gcd(a, b).
| x | <code>bigint</code> |
| y | <code>bigint</code> |
* * *

View File

@ -1,96 +0,0 @@
'use strict';
const rollup = require('rollup');
const resolve = require('@rollup/plugin-node-resolve');
const replace = require('@rollup/plugin-replace');
const commonjs = require('@rollup/plugin-commonjs');
const multi = require('@rollup/plugin-multi-entry');
const fs = require('fs');
const path = require('path');
const pkgJson = require('../package.json');
const pkg_name = pkgJson.name;
const mocha_version = pkgJson.devDependencies.mocha.replace(/[\^~*><=]/g, '');
const chai_version = pkgJson.devDependencies.chai.replace(/[\^~*><=]/g, '');
const rootDir = path.join(__dirname, '..');
// Let's first create the appropriate html file loading mocha, chai and a bundle of the tests
const templatePath = path.join(rootDir, pkgJson.directories.src, 'browser-test-template.html');
const dstDir = path.join(rootDir, pkgJson.directories.test, 'browser');
const dstFileName = path.join(dstDir, 'index.html');
const template = fs.readFileSync(templatePath, 'utf-8');
const bundleFile = path.join(rootDir, pkgJson.directories.dist, pkgJson.name + '-latest.browser.mod.min.js');
const testsJs = `
<script type="module">
import * as ${camelise(pkg_name)} from '${path.relative(templatePath, bundleFile)}'
window.${camelise(pkg_name)} = ${camelise(pkg_name)};
import './tests.js';
mocha.run();
</script>
`;
fs.writeFileSync(dstFileName,
template.replace(/{{TESTS}}/g, testsJs).replace(/{{PKG_NAME}}/g, pkgJson.name).replace(/{{MOCHA_VERSION}}/g, mocha_version).replace(/{{CHAI_VERSION}}/g, chai_version)
);
/*
Now we create a bundle of all the tests called test.js
require/import of the module and chai are removed since they will be loaded from the html file
*/
const distFile = path.relative(path.join(rootDir, 'test'), pkgJson.main);
const requireModuleLine = `const ${camelise(pkgJson.name)} = require('${path.join(path.dirname(distFile), path.basename(distFile, '.js'))}');`;
const buildOptions = [
{ // Browser
input: {
input: path.join(rootDir, 'test', '*.js'),
external: ['chai'],
plugins: [
multi({ exports: false }),
replace({
'const chai = require(\'chai\');': '',
[requireModuleLine]: '',
'delimiters': ['', ''],
'process.browser': true
}),
resolve({
browser: true,
}),
commonjs()
],
},
output: {
file: path.join(rootDir, 'test', 'browser', 'tests.js'),
format: 'esm'
}
}
];
for (const options of buildOptions) {
build(options);
}
/* --- HELPLER FUNCTIONS --- */
async function build(options) {
// create a bundle
const bundle = await rollup.rollup(options.input);
// generate code
await bundle.generate(options.output);
// or write the bundle to disk
await bundle.write(options.output);
}
function camelise(str) {
return str.replace(/-([a-z])/g,
function (m, w) {
return w.toUpperCase();
});
}

View File

@ -1,26 +1,25 @@
const fs = require('fs');
const ts = require('typescript');
const path = require('path');
const pkgJson = require('../package.json');
const rootDir = path.join(__dirname, '..');
const jsFile = path.join(rootDir, pkgJson.browser);
const dtsFile = path.join(rootDir, 'types', `${pkgJson.name}.d.ts`);
const fs = require('fs')
const ts = require('typescript')
const path = require('path')
const pkgJson = require('../package.json')
const rootDir = path.join(__dirname, '..')
const jsFile = path.join(rootDir, pkgJson.browser)
const dtsFile = path.join(rootDir, pkgJson.types)
const compilerOptions = {
'declaration': true,
'noEmit': false,
'emitDeclarationOnly': true,
'allowJs': true
};
declaration: true,
noEmit: false,
emitDeclarationOnly: true,
allowJs: true
}
const host = ts.createCompilerHost(compilerOptions);
const host = ts.createCompilerHost(compilerOptions)
host.writeFile = (fileName, contents) => {
fs.writeFileSync(dtsFile, contents);
};
fs.writeFileSync(dtsFile, contents)
}
// Prepare and emit the d.ts files
const program = ts.createProgram([jsFile], compilerOptions, host);
program.emit();
const program = ts.createProgram([jsFile], compilerOptions, host)
program.emit()

View File

@ -1,128 +0,0 @@
'use strict';
const rollup = require('rollup');
const replace = require('@rollup/plugin-replace');
const terser = require('rollup-plugin-terser');
const fs = require('fs');
const path = require('path');
const pkgJson = require('../package.json');
const rootDir = path.join(__dirname, '..');
const srcDir = path.join(rootDir, 'src');
const dstDir = path.join(rootDir, 'dist');
const buildOptions = [
{ // Browser
input: {
input: path.join(srcDir, 'main.js'),
plugins: [
replace({
'process.browser': true
})
]
},
output: {
file: path.join(dstDir, `${pkgJson.name}-${pkgJson.version}.browser.js`),
format: 'iife',
name: camelise(pkgJson.name)
}
},
{ // Browser minified
input: {
input: path.join(srcDir, 'main.js'),
plugins: [
replace({
'process.browser': true
})
],
},
output: {
file: path.join(dstDir, `${pkgJson.name}-${pkgJson.version}.browser.min.js`),
format: 'iife',
name: camelise(pkgJson.name),
plugins: [
terser.terser({
'mangle': false
})
]
}
},
{ // Browser esm
input: {
input: path.join(srcDir, 'main.js'),
plugins: [
replace({
'process.browser': true
})
]
},
output: {
file: path.join(dstDir, `${pkgJson.name}-${pkgJson.version}.browser.mod.js`),
format: 'esm'
}
},
{ // Browser esm minified
input: {
input: path.join(srcDir, 'main.js'),
plugins: [
replace({
'process.browser': true
})
],
},
output: {
file: path.join(dstDir, `${pkgJson.name}-${pkgJson.version}.browser.mod.min.js`),
format: 'esm',
plugins: [
terser.terser({
'mangle': false
})
]
}
},
{ // Node
input: {
input: path.join(srcDir, 'main.js'),
plugins: [
replace({
'process.browser': false
})
]
},
output: {
file: path.join(dstDir, `${pkgJson.name}-${pkgJson.version}.node.js`),
format: 'cjs'
}
}
];
for (const options of buildOptions) {
build(options);
}
/* --- HELPLER FUNCTIONS --- */
async function build(options) {
// create a bundle
const bundle = await rollup.rollup(options.input);
// generate code
await bundle.generate(options.output);
// or write the bundle to disk
await bundle.write(options.output);
// copy the latest build as pkg_name-latest
fs.copyFileSync(
options.output.file,
options.output.file.replace(`${pkgJson.name}-${pkgJson.version}.`, `${pkgJson.name}-latest.`)
);
}
function camelise(str) {
return str.replace(/-([a-z])/g,
function (m, w) {
return w.toUpperCase();
});
}

82
build/rollup.config.js Normal file
View File

@ -0,0 +1,82 @@
'use strict'
const resolve = require('@rollup/plugin-node-resolve')
const replace = require('@rollup/plugin-replace')
const { terser } = require('rollup-plugin-terser')
const path = require('path')
const pkgJson = require('../package.json')
const rootDir = path.join(__dirname, '..')
const srcDir = path.join(rootDir, pkgJson.directories.src)
const dstDir = path.join(rootDir, pkgJson.directories.lib)
function camelise (str) {
console.log('camelise', str)
return str.replace(/-([a-z])/g,
function (m, w) {
return w.toUpperCase()
})
}
const pkgName = pkgJson.name
const pkgCamelisedName = camelise(pkgName)
const input = path.join(srcDir, 'js', 'index.js')
module.exports = [
{ // ESM native module
input: input,
output: [
{
file: path.join(dstDir, 'index.browser.mod.js'),
format: 'esm'
}
],
plugins: [
replace({
'process.browser': true
})
]
// external: ['bigint-crypto-utils']
},
{ // Browser bundles
input: input,
output: [
{
file: path.join(dstDir, 'index.browser.bundle.js'),
format: 'iife',
name: pkgCamelisedName
},
{
file: path.join(dstDir, 'index.browser.bundle.mod.js'),
format: 'es'
}
],
plugins: [
replace({
'process.browser': true
}),
resolve({
browser: true
}),
terser({
mangle: false,
compress: false
})
]
},
{ // Node
input: input,
plugins: [
replace({
'process.browser': false
})
],
output: {
file: path.join(dstDir, 'index.node.js'),
format: 'cjs'
}
// external: ['bigint-crypto-utils']
}
]

View File

@ -0,0 +1,62 @@
'use strict'
const resolve = require('@rollup/plugin-node-resolve')
const replace = require('@rollup/plugin-replace')
const commonjs = require('@rollup/plugin-commonjs')
const multi = require('@rollup/plugin-multi-entry')
const fs = require('fs')
const path = require('path')
const pkgJson = require('../package.json')
const pkgJsonLock = require('../package-lock.json')
const mochaVersion = pkgJsonLock.dependencies.mocha.version
const chaiVersion = pkgJsonLock.dependencies.chai.version
const pkgName = pkgJson.name
const rootDir = path.join(__dirname, '..')
// Let's first create the appropriate html file loading mocha, chai and a bundle of the tests
const templatePath = path.join(rootDir, pkgJson.directories.src, 'browser', 'tests-template.html')
const dstDir = path.join(rootDir, pkgJson.directories.test, 'browser')
const dstFileName = path.join(dstDir, 'index.html')
const template = fs.readFileSync(templatePath, 'utf-8')
const bundleFile = path.join(rootDir, pkgJson.directories.lib, 'index.browser.bundle.mod.js')
const testsJs = `
<script type="module">
import * as _pkg from '${path.relative(templatePath, bundleFile)}'
window._pkg = _pkg;
import './tests.js';
mocha.run();
</script>`
fs.writeFileSync(dstFileName,
template.replace(/{{TESTS}}/g, testsJs).replace(/{{PKG_NAME}}/g, pkgName).replace(/{{MOCHA_VERSION}}/g, mochaVersion).replace(/{{CHAI_VERSION}}/g, chaiVersion)
)
const input = path.join(rootDir, pkgJson.directories.test, '*.js')
console.log(input)
module.exports = [
{
input: input,
plugins: [
multi({ exports: false }),
replace({
'const _pkg = require(\'../lib/index.node\')': '',
'const chai = require(\'chai\')': '',
delimiters: ['', ''],
'process.browser': true
}),
resolve({
browser: true
}),
commonjs()
],
output: {
file: path.join(rootDir, pkgJson.directories.test, 'browser', 'tests.js'),
format: 'esm'
},
external: [pkgName]
}
]

View File

@ -1,817 +0,0 @@
var bigintCryptoUtils = (function (exports) {
'use strict';
const _ZERO = BigInt(0);
const _ONE = BigInt(1);
const _TWO = BigInt(2);
/**
* Absolute value. abs(a)==a if a>=0. abs(a)==-a if a<0
*
* @param {number | bigint} a
*
* @returns {bigint} the absolute value of a
*/
function abs(a) {
a = BigInt(a);
return (a >= _ZERO) ? a : -a;
}
/**
* Returns the bitlength of a number
*
* @param {number|bigint} a
* @returns {number} - the bit length
*/
function bitLength(a) {
a = BigInt(a);
if (a === _ONE)
return 1;
let bits = 1;
do {
bits++;
} while ((a >>= _ONE) > _ONE);
return bits;
}
/**
* @typedef {Object} egcdReturn A triple (g, x, y), such that ax + by = g = gcd(a, b).
* @property {bigint} g
* @property {bigint} x
* @property {bigint} y
*/
/**
* An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
* Take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {egcdReturn} A triple (g, x, y), such that ax + by = g = gcd(a, b).
*/
function eGcd(a, b) {
a = BigInt(a);
b = BigInt(b);
if (a <= _ZERO | b <= _ZERO)
return NaN; // a and b MUST be positive
let x = _ZERO;
let y = _ONE;
let u = _ONE;
let v = _ZERO;
while (a !== _ZERO) {
let q = b / a;
let r = b % a;
let m = x - (u * q);
let n = y - (v * q);
b = a;
a = r;
x = u;
y = v;
u = m;
v = n;
}
return {
b: b,
x: x,
y: y
};
}
/**
* Greatest-common divisor of two integers based on the iterative binary algorithm.
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The greatest common divisor of a and b
*/
function gcd(a, b) {
a = abs(a);
b = abs(b);
if (a === _ZERO)
return b;
else if (b === _ZERO)
return a;
let shift = _ZERO;
while (!((a | b) & _ONE)) {
a >>= _ONE;
b >>= _ONE;
shift++;
}
while (!(a & _ONE)) a >>= _ONE;
do {
while (!(b & _ONE)) b >>= _ONE;
if (a > b) {
let x = a;
a = b;
b = x;
}
b -= a;
} while (b);
// rescale
return a << shift;
}
/**
* The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
* iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)
*
* @param {number|bigint} w An integer to be tested for primality
* @param {number} [iterations = 16] The number of iterations for the primality test. The value shall be consistent with Table C.1, C.2 or C.3
*
* @returns {Promise<boolean>} A promise that resolves to a boolean that is either true (a probably prime number) or false (definitely composite)
*/
async function isProbablyPrime(w, iterations = 16) {
if (typeof w === 'number') {
w = BigInt(w);
}
{ // browser
return new Promise((resolve, reject) => {
const worker = new Worker(_isProbablyPrimeWorkerUrl());
worker.onmessage = (event) => {
worker.terminate();
resolve(event.data.isPrime);
};
worker.onmessageerror = (event) => {
reject(event);
};
worker.postMessage({
'rnd': w,
'iterations': iterations,
'id': 0
});
});
}
}
/**
* The least common multiple computed as abs(a*b)/gcd(a,b)
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The least common multiple of a and b
*/
function lcm(a, b) {
a = BigInt(a);
b = BigInt(b);
if (a === _ZERO && b === _ZERO)
return _ZERO;
return abs(a * b) / gcd(a, b);
}
/**
* Maximum. max(a,b)==a if a>=b. max(a,b)==b if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} maximum of numbers a and b
*/
function max(a, b) {
a = BigInt(a);
b = BigInt(b);
return (a >= b) ? a : b;
}
/**
* Minimum. min(a,b)==b if a>=b. min(a,b)==a if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} minimum of numbers a and b
*/
function min(a, b) {
a = BigInt(a);
b = BigInt(b);
return (a >= b) ? b : a;
}
/**
* Modular inverse.
*
* @param {number|bigint} a The number to find an inverse for
* @param {number|bigint} n The modulo
*
* @returns {bigint} the inverse modulo n or NaN if it does not exist
*/
function modInv(a, n) {
if (a == _ZERO | n <= _ZERO)
return NaN;
let egcd = eGcd(toZn(a, n), n);
if (egcd.b !== _ONE) {
return NaN; // modular inverse does not exist
} else {
return toZn(egcd.x, n);
}
}
/**
* Modular exponentiation b**e mod n. Currently using the right-to-left binary method
*
* @param {number|bigint} b base
* @param {number|bigint} e exponent
* @param {number|bigint} n modulo
*
* @returns {bigint} b**e mod n
*/
function modPow(b, e, n) {
n = BigInt(n);
if (n === _ZERO)
return NaN;
else if (n === _ONE)
return _ZERO;
b = toZn(b, n);
e = BigInt(e);
if (e < _ZERO) {
return modInv(modPow(b, abs(e), n), n);
}
let r = _ONE;
while (e > 0) {
if ((e % _TWO) === _ONE) {
r = (r * b) % n;
}
e = e / _TWO;
b = b ** _TWO % n;
}
return r;
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
* main process, and it can be much faster (if several cores or cpu are available).
* The node version can also use worker_threads if they are available (enabled by default with Node 11 and
* and can be enabled at runtime executing node --experimental-worker with node >=10.5.0).
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {Promise<bigint>} A promise that resolves to a bigint probable prime of bitLength bits.
*/
function prime(bitLength, iterations = 16) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
return new Promise((resolve) => {
let workerList = [];
const _onmessage = (msg, newWorker) => {
if (msg.isPrime) {
// if a prime number has been found, stop all the workers, and return it
for (let j = 0; j < workerList.length; j++) {
workerList[j].terminate();
}
while (workerList.length) {
workerList.pop();
}
resolve(msg.value);
} else { // if a composite is found, make the worker test another random number
let buf = randBits(bitLength, true);
let rnd = fromBuffer(buf);
try {
newWorker.postMessage({
'rnd': rnd,
'iterations': iterations,
'id': msg.id
});
} catch (error) {
// The worker has already terminated. There is nothing to handle here
}
}
};
{ //browser
let workerURL = _isProbablyPrimeWorkerUrl();
for (let i = 0; i < self.navigator.hardwareConcurrency; i++) {
let newWorker = new Worker(workerURL);
newWorker.onmessage = (event) => _onmessage(event.data, newWorker);
workerList.push(newWorker);
}
}
for (let i = 0; i < workerList.length; i++) {
let buf = randBits(bitLength, true);
let rnd = fromBuffer(buf);
workerList[i].postMessage({
'rnd': rnd,
'iterations': iterations,
'id': i
});
}
});
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The sync version is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript. Please consider using prime() instead.
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {bigint} A bigint probable prime of bitLength bits.
*/
function primeSync(bitLength, iterations = 16) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
let rnd = _ZERO;
do {
rnd = fromBuffer(randBytesSync(bitLength / 8, true));
} while (!_isProbablyPrime(rnd, iterations));
return rnd;
}
/**
* Returns a cryptographically secure random integer between [min,max]
* @param {bigint} max Returned value will be <= max
* @param {bigint} [min = BigInt(1)] Returned value will be >= min
*
* @returns {bigint} A cryptographically secure random bigint between [min,max]
*/
function randBetween(max, min = _ONE) {
if (max <= min) throw new Error('max must be > min');
const interval = max - min;
let bitLen = bitLength(interval);
let rnd;
do {
let buf = randBits(bitLen);
rnd = fromBuffer(buf);
} while (rnd > interval);
return rnd + min;
}
/**
* Secure random bits for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} bitLength The desired number of random bits
* @param {boolean} [forceLength = false] If we want to force the output to have a specific bit length. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bits
*/
function randBits(bitLength, forceLength = false) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
const byteLength = Math.ceil(bitLength / 8);
const rndBytes = randBytesSync(byteLength, false);
const bitLengthMod8 = bitLength % 8;
if (bitLengthMod8) {
// Fill with 0's the extra bits
rndBytes[0] = rndBytes[0] & (2 ** bitLengthMod8 - 1);
}
if (forceLength) {
const mask = bitLengthMod8 ? 2 ** (bitLengthMod8 - 1) : 128;
rndBytes[0] = rndBytes[0] | mask;
}
return rndBytes;
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Promise<Buffer|Uint8Array>} A promise that resolves to a Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytes(byteLength, forceLength = false) {
if (byteLength < 1)
throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`);
let buf;
{ // browser
return new Promise(function (resolve) {
buf = new Uint8Array(byteLength);
self.crypto.getRandomValues(buf);
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength)
buf[0] = buf[0] | 128;
resolve(buf);
});
}
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytesSync(byteLength, forceLength = false) {
if (byteLength < 1)
throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`);
let buf;
{ // browser
buf = new Uint8Array(byteLength);
self.crypto.getRandomValues(buf);
}
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength)
buf[0] = buf[0] | 128;
return buf;
}
/**
* Finds the smallest positive element that is congruent to a in modulo n
* @param {number|bigint} a An integer
* @param {number|bigint} n The modulo
*
* @returns {bigint} The smallest positive representation of a in modulo n
*/
function toZn(a, n) {
n = BigInt(n);
if (n <= 0)
return NaN;
a = BigInt(a) % n;
return (a < 0) ? a + n : a;
}
/* HELPER FUNCTIONS */
function fromBuffer(buf) {
let ret = _ZERO;
for (let i of buf.values()) {
let bi = BigInt(i);
ret = (ret << BigInt(8)) + bi;
}
return ret;
}
function _isProbablyPrimeWorkerUrl() {
// Let's us first add all the required functions
let workerCode = `'use strict';const _ZERO = BigInt(0);const _ONE = BigInt(1);const _TWO = BigInt(2);const eGcd = ${eGcd.toString()};const modInv = ${modInv.toString()};const modPow = ${modPow.toString()};const toZn = ${toZn.toString()};const randBits = ${randBits.toString()};const randBytesSync = ${randBytesSync.toString()};const randBetween = ${randBetween.toString()};const isProbablyPrime = ${_isProbablyPrime.toString()};${bitLength.toString()}${fromBuffer.toString()}`;
const onmessage = async function (event) { // Let's start once we are called
// event.data = {rnd: <bigint>, iterations: <number>}
const isPrime = await isProbablyPrime(event.data.rnd, event.data.iterations);
postMessage({
'isPrime': isPrime,
'value': event.data.rnd,
'id': event.data.id
});
};
workerCode += `onmessage = ${onmessage.toString()};`;
return _workerUrl(workerCode);
}
function _workerUrl(workerCode) {
workerCode = `(() => {${workerCode}})()`; // encapsulate IIFE
const _blob = new Blob([workerCode], { type: 'text/javascript' });
return window.URL.createObjectURL(_blob);
}
function _isProbablyPrime(w, iterations = 16) {
/*
PREFILTERING. Even values but 2 are not primes, so don't test.
1 is not a prime and the M-R algorithm needs w>1.
*/
if (w === _TWO)
return true;
else if ((w & _ONE) === _ZERO || w === _ONE)
return false;
/*
Test if any of the first 250 small primes are a factor of w. 2 is not tested because it was already tested above.
*/
const firstPrimes = [
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
1009,
1013,
1019,
1021,
1031,
1033,
1039,
1049,
1051,
1061,
1063,
1069,
1087,
1091,
1093,
1097,
1103,
1109,
1117,
1123,
1129,
1151,
1153,
1163,
1171,
1181,
1187,
1193,
1201,
1213,
1217,
1223,
1229,
1231,
1237,
1249,
1259,
1277,
1279,
1283,
1289,
1291,
1297,
1301,
1303,
1307,
1319,
1321,
1327,
1361,
1367,
1373,
1381,
1399,
1409,
1423,
1427,
1429,
1433,
1439,
1447,
1451,
1453,
1459,
1471,
1481,
1483,
1487,
1489,
1493,
1499,
1511,
1523,
1531,
1543,
1549,
1553,
1559,
1567,
1571,
1579,
1583,
1597,
];
for (let i = 0; i < firstPrimes.length && (BigInt(firstPrimes[i]) <= w); i++) {
const p = BigInt(firstPrimes[i]);
if (w === p)
return true;
else if (w % p === _ZERO)
return false;
}
/*
1. Let a be the largest integer such that 2**a divides w1.
2. m = (w1) / 2**a.
3. wlen = len (w).
4. For i = 1 to iterations do
4.1 Obtain a string b of wlen bits from an RBG.
Comment: Ensure that 1 < b < w1.
4.2 If ((b 1) or (b w1)), then go to step 4.1.
4.3 z = b**m mod w.
4.4 If ((z = 1) or (z = w 1)), then go to step 4.7.
4.5 For j = 1 to a 1 do.
4.5.1 z = z**2 mod w.
4.5.2 If (z = w1), then go to step 4.7.
4.5.3 If (z = 1), then go to step 4.6.
4.6 Return COMPOSITE.
4.7 Continue.
Comment: Increment i for the do-loop in step 4.
5. Return PROBABLY PRIME.
*/
let a = _ZERO, d = w - _ONE;
while (d % _TWO === _ZERO) {
d /= _TWO;
++a;
}
let m = (w - _ONE) / (_TWO ** a);
loop: do {
let b = randBetween(w - _ONE, _TWO);
let z = modPow(b, m, w);
if (z === _ONE || z === w - _ONE)
continue;
for (let j = 1; j < a; j++) {
z = modPow(z, _TWO, w);
if (z === w - _ONE)
continue loop;
if (z === _ONE)
break;
}
return false;
} while (--iterations);
return true;
}
exports.abs = abs;
exports.bitLength = bitLength;
exports.eGcd = eGcd;
exports.gcd = gcd;
exports.isProbablyPrime = isProbablyPrime;
exports.lcm = lcm;
exports.max = max;
exports.min = min;
exports.modInv = modInv;
exports.modPow = modPow;
exports.prime = prime;
exports.primeSync = primeSync;
exports.randBetween = randBetween;
exports.randBits = randBits;
exports.randBytes = randBytes;
exports.randBytesSync = randBytesSync;
exports.toZn = toZn;
return exports;
}({}));

File diff suppressed because one or more lines are too long

View File

@ -1,794 +0,0 @@
const _ZERO = BigInt(0);
const _ONE = BigInt(1);
const _TWO = BigInt(2);
/**
* Absolute value. abs(a)==a if a>=0. abs(a)==-a if a<0
*
* @param {number | bigint} a
*
* @returns {bigint} the absolute value of a
*/
function abs(a) {
a = BigInt(a);
return (a >= _ZERO) ? a : -a;
}
/**
* Returns the bitlength of a number
*
* @param {number|bigint} a
* @returns {number} - the bit length
*/
function bitLength(a) {
a = BigInt(a);
if (a === _ONE)
return 1;
let bits = 1;
do {
bits++;
} while ((a >>= _ONE) > _ONE);
return bits;
}
/**
* @typedef {Object} egcdReturn A triple (g, x, y), such that ax + by = g = gcd(a, b).
* @property {bigint} g
* @property {bigint} x
* @property {bigint} y
*/
/**
* An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
* Take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {egcdReturn} A triple (g, x, y), such that ax + by = g = gcd(a, b).
*/
function eGcd(a, b) {
a = BigInt(a);
b = BigInt(b);
if (a <= _ZERO | b <= _ZERO)
return NaN; // a and b MUST be positive
let x = _ZERO;
let y = _ONE;
let u = _ONE;
let v = _ZERO;
while (a !== _ZERO) {
let q = b / a;
let r = b % a;
let m = x - (u * q);
let n = y - (v * q);
b = a;
a = r;
x = u;
y = v;
u = m;
v = n;
}
return {
b: b,
x: x,
y: y
};
}
/**
* Greatest-common divisor of two integers based on the iterative binary algorithm.
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The greatest common divisor of a and b
*/
function gcd(a, b) {
a = abs(a);
b = abs(b);
if (a === _ZERO)
return b;
else if (b === _ZERO)
return a;
let shift = _ZERO;
while (!((a | b) & _ONE)) {
a >>= _ONE;
b >>= _ONE;
shift++;
}
while (!(a & _ONE)) a >>= _ONE;
do {
while (!(b & _ONE)) b >>= _ONE;
if (a > b) {
let x = a;
a = b;
b = x;
}
b -= a;
} while (b);
// rescale
return a << shift;
}
/**
* The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
* iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)
*
* @param {number|bigint} w An integer to be tested for primality
* @param {number} [iterations = 16] The number of iterations for the primality test. The value shall be consistent with Table C.1, C.2 or C.3
*
* @returns {Promise<boolean>} A promise that resolves to a boolean that is either true (a probably prime number) or false (definitely composite)
*/
async function isProbablyPrime(w, iterations = 16) {
if (typeof w === 'number') {
w = BigInt(w);
}
{ // browser
return new Promise((resolve, reject) => {
const worker = new Worker(_isProbablyPrimeWorkerUrl());
worker.onmessage = (event) => {
worker.terminate();
resolve(event.data.isPrime);
};
worker.onmessageerror = (event) => {
reject(event);
};
worker.postMessage({
'rnd': w,
'iterations': iterations,
'id': 0
});
});
}
}
/**
* The least common multiple computed as abs(a*b)/gcd(a,b)
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The least common multiple of a and b
*/
function lcm(a, b) {
a = BigInt(a);
b = BigInt(b);
if (a === _ZERO && b === _ZERO)
return _ZERO;
return abs(a * b) / gcd(a, b);
}
/**
* Maximum. max(a,b)==a if a>=b. max(a,b)==b if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} maximum of numbers a and b
*/
function max(a, b) {
a = BigInt(a);
b = BigInt(b);
return (a >= b) ? a : b;
}
/**
* Minimum. min(a,b)==b if a>=b. min(a,b)==a if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} minimum of numbers a and b
*/
function min(a, b) {
a = BigInt(a);
b = BigInt(b);
return (a >= b) ? b : a;
}
/**
* Modular inverse.
*
* @param {number|bigint} a The number to find an inverse for
* @param {number|bigint} n The modulo
*
* @returns {bigint} the inverse modulo n or NaN if it does not exist
*/
function modInv(a, n) {
if (a == _ZERO | n <= _ZERO)
return NaN;
let egcd = eGcd(toZn(a, n), n);
if (egcd.b !== _ONE) {
return NaN; // modular inverse does not exist
} else {
return toZn(egcd.x, n);
}
}
/**
* Modular exponentiation b**e mod n. Currently using the right-to-left binary method
*
* @param {number|bigint} b base
* @param {number|bigint} e exponent
* @param {number|bigint} n modulo
*
* @returns {bigint} b**e mod n
*/
function modPow(b, e, n) {
n = BigInt(n);
if (n === _ZERO)
return NaN;
else if (n === _ONE)
return _ZERO;
b = toZn(b, n);
e = BigInt(e);
if (e < _ZERO) {
return modInv(modPow(b, abs(e), n), n);
}
let r = _ONE;
while (e > 0) {
if ((e % _TWO) === _ONE) {
r = (r * b) % n;
}
e = e / _TWO;
b = b ** _TWO % n;
}
return r;
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
* main process, and it can be much faster (if several cores or cpu are available).
* The node version can also use worker_threads if they are available (enabled by default with Node 11 and
* and can be enabled at runtime executing node --experimental-worker with node >=10.5.0).
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {Promise<bigint>} A promise that resolves to a bigint probable prime of bitLength bits.
*/
function prime(bitLength, iterations = 16) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
return new Promise((resolve) => {
let workerList = [];
const _onmessage = (msg, newWorker) => {
if (msg.isPrime) {
// if a prime number has been found, stop all the workers, and return it
for (let j = 0; j < workerList.length; j++) {
workerList[j].terminate();
}
while (workerList.length) {
workerList.pop();
}
resolve(msg.value);
} else { // if a composite is found, make the worker test another random number
let buf = randBits(bitLength, true);
let rnd = fromBuffer(buf);
try {
newWorker.postMessage({
'rnd': rnd,
'iterations': iterations,
'id': msg.id
});
} catch (error) {
// The worker has already terminated. There is nothing to handle here
}
}
};
{ //browser
let workerURL = _isProbablyPrimeWorkerUrl();
for (let i = 0; i < self.navigator.hardwareConcurrency; i++) {
let newWorker = new Worker(workerURL);
newWorker.onmessage = (event) => _onmessage(event.data, newWorker);
workerList.push(newWorker);
}
}
for (let i = 0; i < workerList.length; i++) {
let buf = randBits(bitLength, true);
let rnd = fromBuffer(buf);
workerList[i].postMessage({
'rnd': rnd,
'iterations': iterations,
'id': i
});
}
});
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The sync version is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript. Please consider using prime() instead.
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {bigint} A bigint probable prime of bitLength bits.
*/
function primeSync(bitLength, iterations = 16) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
let rnd = _ZERO;
do {
rnd = fromBuffer(randBytesSync(bitLength / 8, true));
} while (!_isProbablyPrime(rnd, iterations));
return rnd;
}
/**
* Returns a cryptographically secure random integer between [min,max]
* @param {bigint} max Returned value will be <= max
* @param {bigint} [min = BigInt(1)] Returned value will be >= min
*
* @returns {bigint} A cryptographically secure random bigint between [min,max]
*/
function randBetween(max, min = _ONE) {
if (max <= min) throw new Error('max must be > min');
const interval = max - min;
let bitLen = bitLength(interval);
let rnd;
do {
let buf = randBits(bitLen);
rnd = fromBuffer(buf);
} while (rnd > interval);
return rnd + min;
}
/**
* Secure random bits for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} bitLength The desired number of random bits
* @param {boolean} [forceLength = false] If we want to force the output to have a specific bit length. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bits
*/
function randBits(bitLength, forceLength = false) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
const byteLength = Math.ceil(bitLength / 8);
const rndBytes = randBytesSync(byteLength, false);
const bitLengthMod8 = bitLength % 8;
if (bitLengthMod8) {
// Fill with 0's the extra bits
rndBytes[0] = rndBytes[0] & (2 ** bitLengthMod8 - 1);
}
if (forceLength) {
const mask = bitLengthMod8 ? 2 ** (bitLengthMod8 - 1) : 128;
rndBytes[0] = rndBytes[0] | mask;
}
return rndBytes;
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Promise<Buffer|Uint8Array>} A promise that resolves to a Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytes(byteLength, forceLength = false) {
if (byteLength < 1)
throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`);
let buf;
{ // browser
return new Promise(function (resolve) {
buf = new Uint8Array(byteLength);
self.crypto.getRandomValues(buf);
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength)
buf[0] = buf[0] | 128;
resolve(buf);
});
}
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytesSync(byteLength, forceLength = false) {
if (byteLength < 1)
throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`);
let buf;
{ // browser
buf = new Uint8Array(byteLength);
self.crypto.getRandomValues(buf);
}
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength)
buf[0] = buf[0] | 128;
return buf;
}
/**
* Finds the smallest positive element that is congruent to a in modulo n
* @param {number|bigint} a An integer
* @param {number|bigint} n The modulo
*
* @returns {bigint} The smallest positive representation of a in modulo n
*/
function toZn(a, n) {
n = BigInt(n);
if (n <= 0)
return NaN;
a = BigInt(a) % n;
return (a < 0) ? a + n : a;
}
/* HELPER FUNCTIONS */
function fromBuffer(buf) {
let ret = _ZERO;
for (let i of buf.values()) {
let bi = BigInt(i);
ret = (ret << BigInt(8)) + bi;
}
return ret;
}
function _isProbablyPrimeWorkerUrl() {
// Let's us first add all the required functions
let workerCode = `'use strict';const _ZERO = BigInt(0);const _ONE = BigInt(1);const _TWO = BigInt(2);const eGcd = ${eGcd.toString()};const modInv = ${modInv.toString()};const modPow = ${modPow.toString()};const toZn = ${toZn.toString()};const randBits = ${randBits.toString()};const randBytesSync = ${randBytesSync.toString()};const randBetween = ${randBetween.toString()};const isProbablyPrime = ${_isProbablyPrime.toString()};${bitLength.toString()}${fromBuffer.toString()}`;
const onmessage = async function (event) { // Let's start once we are called
// event.data = {rnd: <bigint>, iterations: <number>}
const isPrime = await isProbablyPrime(event.data.rnd, event.data.iterations);
postMessage({
'isPrime': isPrime,
'value': event.data.rnd,
'id': event.data.id
});
};
workerCode += `onmessage = ${onmessage.toString()};`;
return _workerUrl(workerCode);
}
function _workerUrl(workerCode) {
workerCode = `(() => {${workerCode}})()`; // encapsulate IIFE
const _blob = new Blob([workerCode], { type: 'text/javascript' });
return window.URL.createObjectURL(_blob);
}
function _isProbablyPrime(w, iterations = 16) {
/*
PREFILTERING. Even values but 2 are not primes, so don't test.
1 is not a prime and the M-R algorithm needs w>1.
*/
if (w === _TWO)
return true;
else if ((w & _ONE) === _ZERO || w === _ONE)
return false;
/*
Test if any of the first 250 small primes are a factor of w. 2 is not tested because it was already tested above.
*/
const firstPrimes = [
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
1009,
1013,
1019,
1021,
1031,
1033,
1039,
1049,
1051,
1061,
1063,
1069,
1087,
1091,
1093,
1097,
1103,
1109,
1117,
1123,
1129,
1151,
1153,
1163,
1171,
1181,
1187,
1193,
1201,
1213,
1217,
1223,
1229,
1231,
1237,
1249,
1259,
1277,
1279,
1283,
1289,
1291,
1297,
1301,
1303,
1307,
1319,
1321,
1327,
1361,
1367,
1373,
1381,
1399,
1409,
1423,
1427,
1429,
1433,
1439,
1447,
1451,
1453,
1459,
1471,
1481,
1483,
1487,
1489,
1493,
1499,
1511,
1523,
1531,
1543,
1549,
1553,
1559,
1567,
1571,
1579,
1583,
1597,
];
for (let i = 0; i < firstPrimes.length && (BigInt(firstPrimes[i]) <= w); i++) {
const p = BigInt(firstPrimes[i]);
if (w === p)
return true;
else if (w % p === _ZERO)
return false;
}
/*
1. Let a be the largest integer such that 2**a divides w1.
2. m = (w1) / 2**a.
3. wlen = len (w).
4. For i = 1 to iterations do
4.1 Obtain a string b of wlen bits from an RBG.
Comment: Ensure that 1 < b < w1.
4.2 If ((b 1) or (b w1)), then go to step 4.1.
4.3 z = b**m mod w.
4.4 If ((z = 1) or (z = w 1)), then go to step 4.7.
4.5 For j = 1 to a 1 do.
4.5.1 z = z**2 mod w.
4.5.2 If (z = w1), then go to step 4.7.
4.5.3 If (z = 1), then go to step 4.6.
4.6 Return COMPOSITE.
4.7 Continue.
Comment: Increment i for the do-loop in step 4.
5. Return PROBABLY PRIME.
*/
let a = _ZERO, d = w - _ONE;
while (d % _TWO === _ZERO) {
d /= _TWO;
++a;
}
let m = (w - _ONE) / (_TWO ** a);
loop: do {
let b = randBetween(w - _ONE, _TWO);
let z = modPow(b, m, w);
if (z === _ONE || z === w - _ONE)
continue;
for (let j = 1; j < a; j++) {
z = modPow(z, _TWO, w);
if (z === w - _ONE)
continue loop;
if (z === _ONE)
break;
}
return false;
} while (--iterations);
return true;
}
export { abs, bitLength, eGcd, gcd, isProbablyPrime, lcm, max, min, modInv, modPow, prime, primeSync, randBetween, randBits, randBytes, randBytesSync, toZn };

File diff suppressed because one or more lines are too long

View File

@ -1,839 +0,0 @@
'use strict';
Object.defineProperty(exports, '__esModule', { value: true });
const _ZERO = BigInt(0);
const _ONE = BigInt(1);
const _TWO = BigInt(2);
/**
* Absolute value. abs(a)==a if a>=0. abs(a)==-a if a<0
*
* @param {number | bigint} a
*
* @returns {bigint} the absolute value of a
*/
function abs(a) {
a = BigInt(a);
return (a >= _ZERO) ? a : -a;
}
/**
* Returns the bitlength of a number
*
* @param {number|bigint} a
* @returns {number} - the bit length
*/
function bitLength(a) {
a = BigInt(a);
if (a === _ONE)
return 1;
let bits = 1;
do {
bits++;
} while ((a >>= _ONE) > _ONE);
return bits;
}
/**
* @typedef {Object} egcdReturn A triple (g, x, y), such that ax + by = g = gcd(a, b).
* @property {bigint} g
* @property {bigint} x
* @property {bigint} y
*/
/**
* An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
* Take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {egcdReturn} A triple (g, x, y), such that ax + by = g = gcd(a, b).
*/
function eGcd(a, b) {
a = BigInt(a);
b = BigInt(b);
if (a <= _ZERO | b <= _ZERO)
return NaN; // a and b MUST be positive
let x = _ZERO;
let y = _ONE;
let u = _ONE;
let v = _ZERO;
while (a !== _ZERO) {
let q = b / a;
let r = b % a;
let m = x - (u * q);
let n = y - (v * q);
b = a;
a = r;
x = u;
y = v;
u = m;
v = n;
}
return {
b: b,
x: x,
y: y
};
}
/**
* Greatest-common divisor of two integers based on the iterative binary algorithm.
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The greatest common divisor of a and b
*/
function gcd(a, b) {
a = abs(a);
b = abs(b);
if (a === _ZERO)
return b;
else if (b === _ZERO)
return a;
let shift = _ZERO;
while (!((a | b) & _ONE)) {
a >>= _ONE;
b >>= _ONE;
shift++;
}
while (!(a & _ONE)) a >>= _ONE;
do {
while (!(b & _ONE)) b >>= _ONE;
if (a > b) {
let x = a;
a = b;
b = x;
}
b -= a;
} while (b);
// rescale
return a << shift;
}
/**
* The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
* iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)
*
* @param {number|bigint} w An integer to be tested for primality
* @param {number} [iterations = 16] The number of iterations for the primality test. The value shall be consistent with Table C.1, C.2 or C.3
*
* @returns {Promise<boolean>} A promise that resolves to a boolean that is either true (a probably prime number) or false (definitely composite)
*/
async function isProbablyPrime(w, iterations = 16) {
if (typeof w === 'number') {
w = BigInt(w);
}
{ // Node.js
if (_useWorkers) {
const { Worker } = require('worker_threads');
return new Promise((resolve, reject) => {
const worker = new Worker(__filename);
worker.on('message', (data) => {
worker.terminate();
resolve(data.isPrime);
});
worker.on('error', reject);
worker.postMessage({
'rnd': w,
'iterations': iterations,
'id': 0
});
});
} else {
return new Promise((resolve) => {
resolve(_isProbablyPrime(w, iterations));
});
}
}
}
/**
* The least common multiple computed as abs(a*b)/gcd(a,b)
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The least common multiple of a and b
*/
function lcm(a, b) {
a = BigInt(a);
b = BigInt(b);
if (a === _ZERO && b === _ZERO)
return _ZERO;
return abs(a * b) / gcd(a, b);
}
/**
* Maximum. max(a,b)==a if a>=b. max(a,b)==b if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} maximum of numbers a and b
*/
function max(a, b) {
a = BigInt(a);
b = BigInt(b);
return (a >= b) ? a : b;
}
/**
* Minimum. min(a,b)==b if a>=b. min(a,b)==a if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} minimum of numbers a and b
*/
function min(a, b) {
a = BigInt(a);
b = BigInt(b);
return (a >= b) ? b : a;
}
/**
* Modular inverse.
*
* @param {number|bigint} a The number to find an inverse for
* @param {number|bigint} n The modulo
*
* @returns {bigint} the inverse modulo n or NaN if it does not exist
*/
function modInv(a, n) {
if (a == _ZERO | n <= _ZERO)
return NaN;
let egcd = eGcd(toZn(a, n), n);
if (egcd.b !== _ONE) {
return NaN; // modular inverse does not exist
} else {
return toZn(egcd.x, n);
}
}
/**
* Modular exponentiation b**e mod n. Currently using the right-to-left binary method
*
* @param {number|bigint} b base
* @param {number|bigint} e exponent
* @param {number|bigint} n modulo
*
* @returns {bigint} b**e mod n
*/
function modPow(b, e, n) {
n = BigInt(n);
if (n === _ZERO)
return NaN;
else if (n === _ONE)
return _ZERO;
b = toZn(b, n);
e = BigInt(e);
if (e < _ZERO) {
return modInv(modPow(b, abs(e), n), n);
}
let r = _ONE;
while (e > 0) {
if ((e % _TWO) === _ONE) {
r = (r * b) % n;
}
e = e / _TWO;
b = b ** _TWO % n;
}
return r;
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
* main process, and it can be much faster (if several cores or cpu are available).
* The node version can also use worker_threads if they are available (enabled by default with Node 11 and
* and can be enabled at runtime executing node --experimental-worker with node >=10.5.0).
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {Promise<bigint>} A promise that resolves to a bigint probable prime of bitLength bits.
*/
function prime(bitLength, iterations = 16) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
if ( !_useWorkers) {
let rnd = _ZERO;
do {
rnd = fromBuffer(randBytesSync(bitLength / 8, true));
} while (!_isProbablyPrime(rnd, iterations));
return new Promise((resolve) => { resolve(rnd); });
}
return new Promise((resolve) => {
let workerList = [];
const _onmessage = (msg, newWorker) => {
if (msg.isPrime) {
// if a prime number has been found, stop all the workers, and return it
for (let j = 0; j < workerList.length; j++) {
workerList[j].terminate();
}
while (workerList.length) {
workerList.pop();
}
resolve(msg.value);
} else { // if a composite is found, make the worker test another random number
let buf = randBits(bitLength, true);
let rnd = fromBuffer(buf);
try {
newWorker.postMessage({
'rnd': rnd,
'iterations': iterations,
'id': msg.id
});
} catch (error) {
// The worker has already terminated. There is nothing to handle here
}
}
};
{ // Node.js
const { cpus } = require('os');
const { Worker } = require('worker_threads');
for (let i = 0; i < cpus().length; i++) {
let newWorker = new Worker(__filename);
newWorker.on('message', (msg) => _onmessage(msg, newWorker));
workerList.push(newWorker);
}
}
for (let i = 0; i < workerList.length; i++) {
let buf = randBits(bitLength, true);
let rnd = fromBuffer(buf);
workerList[i].postMessage({
'rnd': rnd,
'iterations': iterations,
'id': i
});
}
});
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The sync version is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript. Please consider using prime() instead.
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {bigint} A bigint probable prime of bitLength bits.
*/
function primeSync(bitLength, iterations = 16) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
let rnd = _ZERO;
do {
rnd = fromBuffer(randBytesSync(bitLength / 8, true));
} while (!_isProbablyPrime(rnd, iterations));
return rnd;
}
/**
* Returns a cryptographically secure random integer between [min,max]
* @param {bigint} max Returned value will be <= max
* @param {bigint} [min = BigInt(1)] Returned value will be >= min
*
* @returns {bigint} A cryptographically secure random bigint between [min,max]
*/
function randBetween(max, min = _ONE) {
if (max <= min) throw new Error('max must be > min');
const interval = max - min;
let bitLen = bitLength(interval);
let rnd;
do {
let buf = randBits(bitLen);
rnd = fromBuffer(buf);
} while (rnd > interval);
return rnd + min;
}
/**
* Secure random bits for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} bitLength The desired number of random bits
* @param {boolean} [forceLength = false] If we want to force the output to have a specific bit length. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bits
*/
function randBits(bitLength, forceLength = false) {
if (bitLength < 1)
throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`);
const byteLength = Math.ceil(bitLength / 8);
const rndBytes = randBytesSync(byteLength, false);
const bitLengthMod8 = bitLength % 8;
if (bitLengthMod8) {
// Fill with 0's the extra bits
rndBytes[0] = rndBytes[0] & (2 ** bitLengthMod8 - 1);
}
if (forceLength) {
const mask = bitLengthMod8 ? 2 ** (bitLengthMod8 - 1) : 128;
rndBytes[0] = rndBytes[0] | mask;
}
return rndBytes;
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Promise<Buffer|Uint8Array>} A promise that resolves to a Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytes(byteLength, forceLength = false) {
if (byteLength < 1)
throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`);
let buf;
{ // node
const crypto = require('crypto');
buf = Buffer.alloc(byteLength);
return crypto.randomFill(buf, function (resolve) {
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength)
buf[0] = buf[0] | 128;
resolve(buf);
});
}
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytesSync(byteLength, forceLength = false) {
if (byteLength < 1)
throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`);
let buf;
{ // node
const crypto = require('crypto');
buf = Buffer.alloc(byteLength);
crypto.randomFillSync(buf);
}
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength)
buf[0] = buf[0] | 128;
return buf;
}
/**
* Finds the smallest positive element that is congruent to a in modulo n
* @param {number|bigint} a An integer
* @param {number|bigint} n The modulo
*
* @returns {bigint} The smallest positive representation of a in modulo n
*/
function toZn(a, n) {
n = BigInt(n);
if (n <= 0)
return NaN;
a = BigInt(a) % n;
return (a < 0) ? a + n : a;
}
/* HELPER FUNCTIONS */
function fromBuffer(buf) {
let ret = _ZERO;
for (let i of buf.values()) {
let bi = BigInt(i);
ret = (ret << BigInt(8)) + bi;
}
return ret;
}
function _isProbablyPrime(w, iterations = 16) {
/*
PREFILTERING. Even values but 2 are not primes, so don't test.
1 is not a prime and the M-R algorithm needs w>1.
*/
if (w === _TWO)
return true;
else if ((w & _ONE) === _ZERO || w === _ONE)
return false;
/*
Test if any of the first 250 small primes are a factor of w. 2 is not tested because it was already tested above.
*/
const firstPrimes = [
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
1009,
1013,
1019,
1021,
1031,
1033,
1039,
1049,
1051,
1061,
1063,
1069,
1087,
1091,
1093,
1097,
1103,
1109,
1117,
1123,
1129,
1151,
1153,
1163,
1171,
1181,
1187,
1193,
1201,
1213,
1217,
1223,
1229,
1231,
1237,
1249,
1259,
1277,
1279,
1283,
1289,
1291,
1297,
1301,
1303,
1307,
1319,
1321,
1327,
1361,
1367,
1373,
1381,
1399,
1409,
1423,
1427,
1429,
1433,
1439,
1447,
1451,
1453,
1459,
1471,
1481,
1483,
1487,
1489,
1493,
1499,
1511,
1523,
1531,
1543,
1549,
1553,
1559,
1567,
1571,
1579,
1583,
1597,
];
for (let i = 0; i < firstPrimes.length && (BigInt(firstPrimes[i]) <= w); i++) {
const p = BigInt(firstPrimes[i]);
if (w === p)
return true;
else if (w % p === _ZERO)
return false;
}
/*
1. Let a be the largest integer such that 2**a divides w1.
2. m = (w1) / 2**a.
3. wlen = len (w).
4. For i = 1 to iterations do
4.1 Obtain a string b of wlen bits from an RBG.
Comment: Ensure that 1 < b < w1.
4.2 If ((b 1) or (b w1)), then go to step 4.1.
4.3 z = b**m mod w.
4.4 If ((z = 1) or (z = w 1)), then go to step 4.7.
4.5 For j = 1 to a 1 do.
4.5.1 z = z**2 mod w.
4.5.2 If (z = w1), then go to step 4.7.
4.5.3 If (z = 1), then go to step 4.6.
4.6 Return COMPOSITE.
4.7 Continue.
Comment: Increment i for the do-loop in step 4.
5. Return PROBABLY PRIME.
*/
let a = _ZERO, d = w - _ONE;
while (d % _TWO === _ZERO) {
d /= _TWO;
++a;
}
let m = (w - _ONE) / (_TWO ** a);
loop: do {
let b = randBetween(w - _ONE, _TWO);
let z = modPow(b, m, w);
if (z === _ONE || z === w - _ONE)
continue;
for (let j = 1; j < a; j++) {
z = modPow(z, _TWO, w);
if (z === w - _ONE)
continue loop;
if (z === _ONE)
break;
}
return false;
} while (--iterations);
return true;
}
let _useWorkers = true; // The following is just to check whether Node.js can use workers
{ // Node.js
_useWorkers = (function _workers() {
try {
require.resolve('worker_threads');
return true;
} catch (e) {
console.log(`[bigint-crypto-utils] WARNING:
This node version doesn't support worker_threads. You should enable them in order to greatly speedup the generation of big prime numbers.
· With Node 11 it is enabled by default (consider upgrading).
· With Node 10, starting with 10.5.0, you can enable worker_threads at runtime executing node --experimental-worker `);
return false;
}
})();
}
if ( _useWorkers) { // node.js with support for workers
const { parentPort, isMainThread } = require('worker_threads');
if (!isMainThread) { // worker
parentPort.on('message', function (data) { // Let's start once we are called
// data = {rnd: <bigint>, iterations: <number>}
const isPrime = _isProbablyPrime(data.rnd, data.iterations);
parentPort.postMessage({
'isPrime': isPrime,
'value': data.rnd,
'id': data.id
});
});
}
}
exports.abs = abs;
exports.bitLength = bitLength;
exports.eGcd = eGcd;
exports.gcd = gcd;
exports.isProbablyPrime = isProbablyPrime;
exports.lcm = lcm;
exports.max = max;
exports.min = min;
exports.modInv = modInv;
exports.modPow = modPow;
exports.prime = prime;
exports.primeSync = primeSync;
exports.randBetween = randBetween;
exports.randBits = randBits;
exports.randBytes = randBytes;
exports.randBytesSync = randBytesSync;
exports.toZn = toZn;

File diff suppressed because one or more lines are too long

File diff suppressed because one or more lines are too long

768
lib/index.browser.mod.js Normal file
View File

@ -0,0 +1,768 @@
const _ZERO = BigInt(0)
const _ONE = BigInt(1)
const _TWO = BigInt(2)
/**
* Absolute value. abs(a)==a if a>=0. abs(a)==-a if a<0
*
* @param {number|bigint} a
*
* @returns {bigint} the absolute value of a
*/
function abs (a) {
a = BigInt(a)
return (a >= _ZERO) ? a : -a
}
/**
* Returns the bitlength of a number
*
* @param {number|bigint} a
* @returns {number} - the bit length
*/
function bitLength (a) {
a = BigInt(a)
if (a === _ONE) { return 1 }
let bits = 1
do {
bits++
} while ((a >>= _ONE) > _ONE)
return bits
}
/**
* @typedef {Object} egcdReturn A triple (g, x, y), such that ax + by = g = gcd(a, b).
* @property {bigint} g
* @property {bigint} x
* @property {bigint} y
*/
/**
* An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
* Take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {egcdReturn} A triple (g, x, y), such that ax + by = g = gcd(a, b).
*/
function eGcd (a, b) {
a = BigInt(a)
b = BigInt(b)
if (a <= _ZERO | b <= _ZERO) { return NaN } // a and b MUST be positive
let x = _ZERO
let y = _ONE
let u = _ONE
let v = _ZERO
while (a !== _ZERO) {
const q = b / a
const r = b % a
const m = x - (u * q)
const n = y - (v * q)
b = a
a = r
x = u
y = v
u = m
v = n
}
return {
b: b,
x: x,
y: y
}
}
/**
* Greatest-common divisor of two integers based on the iterative binary algorithm.
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The greatest common divisor of a and b
*/
function gcd (a, b) {
a = abs(a)
b = abs(b)
if (a === _ZERO) { return b } else if (b === _ZERO) { return a }
let shift = _ZERO
while (!((a | b) & _ONE)) {
a >>= _ONE
b >>= _ONE
shift++
}
while (!(a & _ONE)) a >>= _ONE
do {
while (!(b & _ONE)) b >>= _ONE
if (a > b) {
const x = a
a = b
b = x
}
b -= a
} while (b)
// rescale
return a << shift
}
/**
* The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
* iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)
*
* @param {number|bigint} w An integer to be tested for primality
* @param {number} [iterations = 16] The number of iterations for the primality test. The value shall be consistent with Table C.1, C.2 or C.3
*
* @return {Promise} A promise that resolves to a boolean that is either true (a probably prime number) or false (definitely composite)
*/
async function isProbablyPrime (w, iterations = 16) {
if (typeof w === 'number') {
w = BigInt(w)
}
/* eslint-disable no-lone-blocks */
{ // browser
return new Promise((resolve, reject) => {
const worker = new Worker(_isProbablyPrimeWorkerUrl())
worker.onmessage = (event) => {
worker.terminate()
resolve(event.data.isPrime)
}
worker.onmessageerror = (event) => {
reject(event)
}
worker.postMessage({
rnd: w,
iterations: iterations,
id: 0
})
})
}
/* eslint-enable no-lone-blocks */
}
/**
* The least common multiple computed as abs(a*b)/gcd(a,b)
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The least common multiple of a and b
*/
function lcm (a, b) {
a = BigInt(a)
b = BigInt(b)
if (a === _ZERO && b === _ZERO) { return _ZERO }
return abs(a * b) / gcd(a, b)
}
/**
* Maximum. max(a,b)==a if a>=b. max(a,b)==b if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} maximum of numbers a and b
*/
function max (a, b) {
a = BigInt(a)
b = BigInt(b)
return (a >= b) ? a : b
}
/**
* Minimum. min(a,b)==b if a>=b. min(a,b)==a if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} minimum of numbers a and b
*/
function min (a, b) {
a = BigInt(a)
b = BigInt(b)
return (a >= b) ? b : a
}
/**
* Modular inverse.
*
* @param {number|bigint} a The number to find an inverse for
* @param {number|bigint} n The modulo
*
* @returns {bigint} the inverse modulo n or NaN if it does not exist
*/
function modInv (a, n) {
const egcd = eGcd(toZn(a, n), n)
if (egcd.b !== _ONE) {
return NaN // modular inverse does not exist
} else {
return toZn(egcd.x, n)
}
}
/**
* Modular exponentiation b**e mod n. Currently using the right-to-left binary method
*
* @param {number|bigint} b base
* @param {number|bigint} e exponent
* @param {number|bigint} n modulo
*
* @returns {bigint} b**e mod n
*/
function modPow (b, e, n) {
n = BigInt(n)
if (n === _ZERO) { return NaN } else if (n === _ONE) { return _ZERO }
b = toZn(b, n)
e = BigInt(e)
if (e < _ZERO) {
return modInv(modPow(b, abs(e), n), n)
}
let r = _ONE
while (e > 0) {
if ((e % _TWO) === _ONE) {
r = (r * b) % n
}
e = e / _TWO
b = b ** _TWO % n
}
return r
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
* main process, and it can be much faster (if several cores or cpu are available).
* The node version can also use worker_threads if they are available (enabled by default with Node 11 and
* and can be enabled at runtime executing node --experimental-worker with node >=10.5.0).
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {Promise} A promise that resolves to a bigint probable prime of bitLength bits.
*/
function prime (bitLength, iterations = 16) {
if (bitLength < 1) { throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`) }
return new Promise((resolve) => {
const workerList = []
const _onmessage = (msg, newWorker) => {
if (msg.isPrime) {
// if a prime number has been found, stop all the workers, and return it
for (let j = 0; j < workerList.length; j++) {
workerList[j].terminate()
}
while (workerList.length) {
workerList.pop()
}
resolve(msg.value)
} else { // if a composite is found, make the worker test another random number
const buf = randBits(bitLength, true)
const rnd = fromBuffer(buf)
try {
newWorker.postMessage({
rnd: rnd,
iterations: iterations,
id: msg.id
})
} catch (error) {
// The worker has already terminated. There is nothing to handle here
}
}
}
/* eslint-disable no-lone-blocks */
{ // browser
const workerURL = _isProbablyPrimeWorkerUrl()
for (let i = 0; i < self.navigator.hardwareConcurrency; i++) {
const newWorker = new Worker(workerURL)
newWorker.onmessage = (event) => _onmessage(event.data, newWorker)
workerList.push(newWorker)
}
}
/* eslint-enable no-lone-blocks */
for (let i = 0; i < workerList.length; i++) {
const buf = randBits(bitLength, true)
const rnd = fromBuffer(buf)
workerList[i].postMessage({
rnd: rnd,
iterations: iterations,
id: i
})
}
})
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The sync version is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript. Please consider using prime() instead.
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {bigint} A bigint probable prime of bitLength bits.
*/
function primeSync (bitLength, iterations = 16) {
if (bitLength < 1) { throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`) }
let rnd = _ZERO
do {
rnd = fromBuffer(randBytesSync(bitLength / 8, true))
} while (!_isProbablyPrime(rnd, iterations))
return rnd
}
/**
* Returns a cryptographically secure random integer between [min,max]
* @param {bigint} max Returned value will be <= max
* @param {bigint} [min = BigInt(1)] Returned value will be >= min
*
* @returns {bigint} A cryptographically secure random bigint between [min,max]
*/
function randBetween (max, min = _ONE) {
if (max <= min) throw new Error('max must be > min')
const interval = max - min
const bitLen = bitLength(interval)
let rnd
do {
const buf = randBits(bitLen)
rnd = fromBuffer(buf)
} while (rnd > interval)
return rnd + min
}
/**
* Secure random bits for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} bitLength The desired number of random bits
* @param {boolean} [forceLength = false] If we want to force the output to have a specific bit length. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bits
*/
function randBits (bitLength, forceLength = false) {
if (bitLength < 1) { throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`) }
const byteLength = Math.ceil(bitLength / 8)
const rndBytes = randBytesSync(byteLength, false)
// Fill with 0's the extra bits
rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1)
if (forceLength) {
const mask = (bitLength % 8) ? 2 ** ((bitLength % 8) - 1) : 128
rndBytes[0] = rndBytes[0] | mask
}
return rndBytes
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Promise} A promise that resolves to a Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytes (byteLength, forceLength = false) {
if (byteLength < 1) { throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`) }
let buf
/* eslint-disable no-lone-blocks */
{ // browser
return new Promise(function (resolve) {
buf = new Uint8Array(byteLength)
self.crypto.getRandomValues(buf)
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength) { buf[0] = buf[0] | 128 }
resolve(buf)
})
}
/* eslint-disable no-lone-blocks */
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytesSync (byteLength, forceLength = false) {
if (byteLength < 1) { throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`) }
let buf
{ // browser
buf = new Uint8Array(byteLength)
self.crypto.getRandomValues(buf)
}
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength) { buf[0] = buf[0] | 128 }
return buf
}
/**
* Finds the smallest positive element that is congruent to a in modulo n
* @param {number|bigint} a An integer
* @param {number|bigint} n The modulo
*
* @returns {bigint} The smallest positive representation of a in modulo n
*/
function toZn (a, n) {
n = BigInt(n)
if (n <= 0) { return NaN }
a = BigInt(a) % n
return (a < 0) ? a + n : a
}
/* HELPER FUNCTIONS */
function fromBuffer (buf) {
let ret = _ZERO
for (const i of buf.values()) {
const bi = BigInt(i)
ret = (ret << BigInt(8)) + bi
}
return ret
}
function _isProbablyPrimeWorkerUrl () {
// Let's us first add all the required functions
let workerCode = `'use strict';const _ZERO = BigInt(0);const _ONE = BigInt(1);const _TWO = BigInt(2);const eGcd = ${eGcd.toString()};const modInv = ${modInv.toString()};const modPow = ${modPow.toString()};const toZn = ${toZn.toString()};const randBits = ${randBits.toString()};const randBytesSync = ${randBytesSync.toString()};const randBetween = ${randBetween.toString()};const isProbablyPrime = ${_isProbablyPrime.toString()};${bitLength.toString()}${fromBuffer.toString()}`
const onmessage = async function (event) { // Let's start once we are called
// event.data = {rnd: <bigint>, iterations: <number>}
const isPrime = await isProbablyPrime(event.data.rnd, event.data.iterations)
postMessage({
isPrime: isPrime,
value: event.data.rnd,
id: event.data.id
})
}
workerCode += `onmessage = ${onmessage.toString()};`
return _workerUrl(workerCode)
}
function _workerUrl (workerCode) {
workerCode = `(() => {${workerCode}})()` // encapsulate IIFE
const _blob = new Blob([workerCode], { type: 'text/javascript' })
return window.URL.createObjectURL(_blob)
}
function _isProbablyPrime (w, iterations = 16) {
/*
PREFILTERING. Even values but 2 are not primes, so don't test.
1 is not a prime and the M-R algorithm needs w>1.
*/
if (w === _TWO) { return true } else if ((w & _ONE) === _ZERO || w === _ONE) { return false }
/*
Test if any of the first 250 small primes are a factor of w. 2 is not tested because it was already tested above.
*/
const firstPrimes = [
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
1009,
1013,
1019,
1021,
1031,
1033,
1039,
1049,
1051,
1061,
1063,
1069,
1087,
1091,
1093,
1097,
1103,
1109,
1117,
1123,
1129,
1151,
1153,
1163,
1171,
1181,
1187,
1193,
1201,
1213,
1217,
1223,
1229,
1231,
1237,
1249,
1259,
1277,
1279,
1283,
1289,
1291,
1297,
1301,
1303,
1307,
1319,
1321,
1327,
1361,
1367,
1373,
1381,
1399,
1409,
1423,
1427,
1429,
1433,
1439,
1447,
1451,
1453,
1459,
1471,
1481,
1483,
1487,
1489,
1493,
1499,
1511,
1523,
1531,
1543,
1549,
1553,
1559,
1567,
1571,
1579,
1583,
1597
]
for (let i = 0; i < firstPrimes.length && (BigInt(firstPrimes[i]) <= w); i++) {
const p = BigInt(firstPrimes[i])
if (w === p) { return true } else if (w % p === _ZERO) { return false }
}
/*
1. Let a be the largest integer such that 2**a divides w1.
2. m = (w1) / 2**a.
3. wlen = len (w).
4. For i = 1 to iterations do
4.1 Obtain a string b of wlen bits from an RBG.
Comment: Ensure that 1 < b < w1.
4.2 If ((b 1) or (b w1)), then go to step 4.1.
4.3 z = b**m mod w.
4.4 If ((z = 1) or (z = w 1)), then go to step 4.7.
4.5 For j = 1 to a 1 do.
4.5.1 z = z**2 mod w.
4.5.2 If (z = w1), then go to step 4.7.
4.5.3 If (z = 1), then go to step 4.6.
4.6 Return COMPOSITE.
4.7 Continue.
Comment: Increment i for the do-loop in step 4.
5. Return PROBABLY PRIME.
*/
let a = _ZERO; let d = w - _ONE
while (d % _TWO === _ZERO) {
d /= _TWO
++a
}
const m = (w - _ONE) / (_TWO ** a)
/* eslint-disable no-labels */
loop: do {
const b = randBetween(w - _ONE, _TWO)
let z = modPow(b, m, w)
if (z === _ONE || z === w - _ONE) { continue }
for (let j = 1; j < a; j++) {
z = modPow(z, _TWO, w)
if (z === w - _ONE) { continue loop }
if (z === _ONE) { break }
}
return false
} while (--iterations)
/* eslint-enable no-labels */
return true
}
export { abs, bitLength, eGcd, gcd, isProbablyPrime, lcm, max, min, modInv, modPow, prime, primeSync, randBetween, randBits, randBytes, randBytesSync, toZn }

810
lib/index.node.js Normal file
View File

@ -0,0 +1,810 @@
'use strict'
Object.defineProperty(exports, '__esModule', { value: true })
const _ZERO = BigInt(0)
const _ONE = BigInt(1)
const _TWO = BigInt(2)
/**
* Absolute value. abs(a)==a if a>=0. abs(a)==-a if a<0
*
* @param {number|bigint} a
*
* @returns {bigint} the absolute value of a
*/
function abs (a) {
a = BigInt(a)
return (a >= _ZERO) ? a : -a
}
/**
* Returns the bitlength of a number
*
* @param {number|bigint} a
* @returns {number} - the bit length
*/
function bitLength (a) {
a = BigInt(a)
if (a === _ONE) { return 1 }
let bits = 1
do {
bits++
} while ((a >>= _ONE) > _ONE)
return bits
}
/**
* @typedef {Object} egcdReturn A triple (g, x, y), such that ax + by = g = gcd(a, b).
* @property {bigint} g
* @property {bigint} x
* @property {bigint} y
*/
/**
* An iterative implementation of the extended euclidean algorithm or extended greatest common divisor algorithm.
* Take positive integers a, b as input, and return a triple (g, x, y), such that ax + by = g = gcd(a, b).
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {egcdReturn} A triple (g, x, y), such that ax + by = g = gcd(a, b).
*/
function eGcd (a, b) {
a = BigInt(a)
b = BigInt(b)
if (a <= _ZERO | b <= _ZERO) { return NaN } // a and b MUST be positive
let x = _ZERO
let y = _ONE
let u = _ONE
let v = _ZERO
while (a !== _ZERO) {
const q = b / a
const r = b % a
const m = x - (u * q)
const n = y - (v * q)
b = a
a = r
x = u
y = v
u = m
v = n
}
return {
b: b,
x: x,
y: y
}
}
/**
* Greatest-common divisor of two integers based on the iterative binary algorithm.
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The greatest common divisor of a and b
*/
function gcd (a, b) {
a = abs(a)
b = abs(b)
if (a === _ZERO) { return b } else if (b === _ZERO) { return a }
let shift = _ZERO
while (!((a | b) & _ONE)) {
a >>= _ONE
b >>= _ONE
shift++
}
while (!(a & _ONE)) a >>= _ONE
do {
while (!(b & _ONE)) b >>= _ONE
if (a > b) {
const x = a
a = b
b = x
}
b -= a
} while (b)
// rescale
return a << shift
}
/**
* The test first tries if any of the first 250 small primes are a factor of the input number and then passes several
* iterations of Miller-Rabin Probabilistic Primality Test (FIPS 186-4 C.3.1)
*
* @param {number|bigint} w An integer to be tested for primality
* @param {number} [iterations = 16] The number of iterations for the primality test. The value shall be consistent with Table C.1, C.2 or C.3
*
* @return {Promise} A promise that resolves to a boolean that is either true (a probably prime number) or false (definitely composite)
*/
async function isProbablyPrime (w, iterations = 16) {
if (typeof w === 'number') {
w = BigInt(w)
}
/* eslint-disable no-lone-blocks */
{ // Node.js
if (_useWorkers) {
const { Worker } = require('worker_threads')
return new Promise((resolve, reject) => {
const worker = new Worker(__filename)
worker.on('message', (data) => {
worker.terminate()
resolve(data.isPrime)
})
worker.on('error', reject)
worker.postMessage({
rnd: w,
iterations: iterations,
id: 0
})
})
} else {
return new Promise((resolve) => {
resolve(_isProbablyPrime(w, iterations))
})
}
}
/* eslint-enable no-lone-blocks */
}
/**
* The least common multiple computed as abs(a*b)/gcd(a,b)
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} The least common multiple of a and b
*/
function lcm (a, b) {
a = BigInt(a)
b = BigInt(b)
if (a === _ZERO && b === _ZERO) { return _ZERO }
return abs(a * b) / gcd(a, b)
}
/**
* Maximum. max(a,b)==a if a>=b. max(a,b)==b if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} maximum of numbers a and b
*/
function max (a, b) {
a = BigInt(a)
b = BigInt(b)
return (a >= b) ? a : b
}
/**
* Minimum. min(a,b)==b if a>=b. min(a,b)==a if a<=b
*
* @param {number|bigint} a
* @param {number|bigint} b
*
* @returns {bigint} minimum of numbers a and b
*/
function min (a, b) {
a = BigInt(a)
b = BigInt(b)
return (a >= b) ? b : a
}
/**
* Modular inverse.
*
* @param {number|bigint} a The number to find an inverse for
* @param {number|bigint} n The modulo
*
* @returns {bigint} the inverse modulo n or NaN if it does not exist
*/
function modInv (a, n) {
const egcd = eGcd(toZn(a, n), n)
if (egcd.b !== _ONE) {
return NaN // modular inverse does not exist
} else {
return toZn(egcd.x, n)
}
}
/**
* Modular exponentiation b**e mod n. Currently using the right-to-left binary method
*
* @param {number|bigint} b base
* @param {number|bigint} e exponent
* @param {number|bigint} n modulo
*
* @returns {bigint} b**e mod n
*/
function modPow (b, e, n) {
n = BigInt(n)
if (n === _ZERO) { return NaN } else if (n === _ONE) { return _ZERO }
b = toZn(b, n)
e = BigInt(e)
if (e < _ZERO) {
return modInv(modPow(b, abs(e), n), n)
}
let r = _ONE
while (e > 0) {
if ((e % _TWO) === _ONE) {
r = (r * b) % n
}
e = e / _TWO
b = b ** _TWO % n
}
return r
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The browser version uses web workers to parallelise prime look up. Therefore, it does not lock the UI
* main process, and it can be much faster (if several cores or cpu are available).
* The node version can also use worker_threads if they are available (enabled by default with Node 11 and
* and can be enabled at runtime executing node --experimental-worker with node >=10.5.0).
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {Promise} A promise that resolves to a bigint probable prime of bitLength bits.
*/
function prime (bitLength, iterations = 16) {
if (bitLength < 1) { throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`) }
if (!_useWorkers) {
let rnd = _ZERO
do {
rnd = fromBuffer(randBytesSync(bitLength / 8, true))
} while (!_isProbablyPrime(rnd, iterations))
return new Promise((resolve) => { resolve(rnd) })
}
return new Promise((resolve) => {
const workerList = []
const _onmessage = (msg, newWorker) => {
if (msg.isPrime) {
// if a prime number has been found, stop all the workers, and return it
for (let j = 0; j < workerList.length; j++) {
workerList[j].terminate()
}
while (workerList.length) {
workerList.pop()
}
resolve(msg.value)
} else { // if a composite is found, make the worker test another random number
const buf = randBits(bitLength, true)
const rnd = fromBuffer(buf)
try {
newWorker.postMessage({
rnd: rnd,
iterations: iterations,
id: msg.id
})
} catch (error) {
// The worker has already terminated. There is nothing to handle here
}
}
}
/* eslint-disable no-lone-blocks */
{ // Node.js
const { cpus } = require('os')
const { Worker } = require('worker_threads')
for (let i = 0; i < cpus().length; i++) {
const newWorker = new Worker(__filename)
newWorker.on('message', (msg) => _onmessage(msg, newWorker))
workerList.push(newWorker)
}
}
/* eslint-enable no-lone-blocks */
for (let i = 0; i < workerList.length; i++) {
const buf = randBits(bitLength, true)
const rnd = fromBuffer(buf)
workerList[i].postMessage({
rnd: rnd,
iterations: iterations,
id: i
})
}
})
}
/**
* A probably-prime (Miller-Rabin), cryptographically-secure, random-number generator.
* The sync version is NOT RECOMMENDED since it won't use workers and thus it'll be slower and may freeze thw window in browser's javascript. Please consider using prime() instead.
*
* @param {number} bitLength The required bit length for the generated prime
* @param {number} [iterations = 16] The number of iterations for the Miller-Rabin Probabilistic Primality Test
*
* @returns {bigint} A bigint probable prime of bitLength bits.
*/
function primeSync (bitLength, iterations = 16) {
if (bitLength < 1) { throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`) }
let rnd = _ZERO
do {
rnd = fromBuffer(randBytesSync(bitLength / 8, true))
} while (!_isProbablyPrime(rnd, iterations))
return rnd
}
/**
* Returns a cryptographically secure random integer between [min,max]
* @param {bigint} max Returned value will be <= max
* @param {bigint} [min = BigInt(1)] Returned value will be >= min
*
* @returns {bigint} A cryptographically secure random bigint between [min,max]
*/
function randBetween (max, min = _ONE) {
if (max <= min) throw new Error('max must be > min')
const interval = max - min
const bitLen = bitLength(interval)
let rnd
do {
const buf = randBits(bitLen)
rnd = fromBuffer(buf)
} while (rnd > interval)
return rnd + min
}
/**
* Secure random bits for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} bitLength The desired number of random bits
* @param {boolean} [forceLength = false] If we want to force the output to have a specific bit length. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bits
*/
function randBits (bitLength, forceLength = false) {
if (bitLength < 1) { throw new RangeError(`bitLength MUST be > 0 and it is ${bitLength}`) }
const byteLength = Math.ceil(bitLength / 8)
const rndBytes = randBytesSync(byteLength, false)
// Fill with 0's the extra bits
rndBytes[0] = rndBytes[0] & (2 ** (bitLength % 8) - 1)
if (forceLength) {
const mask = (bitLength % 8) ? 2 ** ((bitLength % 8) - 1) : 128
rndBytes[0] = rndBytes[0] | mask
}
return rndBytes
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Promise} A promise that resolves to a Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytes (byteLength, forceLength = false) {
if (byteLength < 1) { throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`) }
let buf
/* eslint-disable no-lone-blocks */
{ // node
const crypto = require('crypto')
buf = Buffer.alloc(byteLength)
return crypto.randomFill(buf, function (resolve) {
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength) { buf[0] = buf[0] | 128 }
resolve(buf)
})
}
/* eslint-disable no-lone-blocks */
}
/**
* Secure random bytes for both node and browsers. Node version uses crypto.randomFill() and browser one self.crypto.getRandomValues()
*
* @param {number} byteLength The desired number of random bytes
* @param {boolean} [forceLength = false] If we want to force the output to have a bit length of 8*byteLength. It basically forces the msb to be 1
*
* @returns {Buffer|Uint8Array} A Buffer/UInt8Array (Node.js/Browser) filled with cryptographically secure random bytes
*/
function randBytesSync (byteLength, forceLength = false) {
if (byteLength < 1) { throw new RangeError(`byteLength MUST be > 0 and it is ${byteLength}`) }
let buf
{ // node
const crypto = require('crypto')
buf = Buffer.alloc(byteLength)
crypto.randomFillSync(buf)
}
// If fixed length is required we put the first bit to 1 -> to get the necessary bitLength
if (forceLength) { buf[0] = buf[0] | 128 }
return buf
}
/**
* Finds the smallest positive element that is congruent to a in modulo n
* @param {number|bigint} a An integer
* @param {number|bigint} n The modulo
*
* @returns {bigint} The smallest positive representation of a in modulo n
*/
function toZn (a, n) {
n = BigInt(n)
if (n <= 0) { return NaN }
a = BigInt(a) % n
return (a < 0) ? a + n : a
}
/* HELPER FUNCTIONS */
function fromBuffer (buf) {
let ret = _ZERO
for (const i of buf.values()) {
const bi = BigInt(i)
ret = (ret << BigInt(8)) + bi
}
return ret
}
function _isProbablyPrime (w, iterations = 16) {
/*
PREFILTERING. Even values but 2 are not primes, so don't test.
1 is not a prime and the M-R algorithm needs w>1.
*/
if (w === _TWO) { return true } else if ((w & _ONE) === _ZERO || w === _ONE) { return false }
/*
Test if any of the first 250 small primes are a factor of w. 2 is not tested because it was already tested above.
*/
const firstPrimes = [
3,
5,
7,
11,
13,
17,
19,
23,
29,
31,
37,
41,
43,
47,
53,
59,
61,
67,
71,
73,
79,
83,
89,
97,
101,
103,
107,
109,
113,
127,
131,
137,
139,
149,
151,
157,
163,
167,
173,
179,
181,
191,
193,
197,
199,
211,
223,
227,
229,
233,
239,
241,
251,
257,
263,
269,
271,
277,
281,
283,
293,
307,
311,
313,
317,
331,
337,
347,
349,
353,
359,
367,
373,
379,
383,
389,
397,
401,
409,
419,
421,
431,
433,
439,
443,
449,
457,
461,
463,
467,
479,
487,
491,
499,
503,
509,
521,
523,
541,
547,
557,
563,
569,
571,
577,
587,
593,
599,
601,
607,
613,
617,
619,
631,
641,
643,
647,
653,
659,
661,
673,
677,
683,
691,
701,
709,
719,
727,
733,
739,
743,
751,
757,
761,
769,
773,
787,
797,
809,
811,
821,
823,
827,
829,
839,
853,
857,
859,
863,
877,
881,
883,
887,
907,
911,
919,
929,
937,
941,
947,
953,
967,
971,
977,
983,
991,
997,
1009,
1013,
1019,
1021,
1031,
1033,
1039,
1049,
1051,
1061,
1063,
1069,
1087,
1091,
1093,
1097,
1103,
1109,
1117,
1123,
1129,
1151,
1153,
1163,
1171,
1181,
1187,
1193,
1201,
1213,
1217,
1223,
1229,
1231,
1237,
1249,
1259,
1277,
1279,
1283,
1289,
1291,
1297,
1301,
1303,
1307,
1319,
1321,
1327,
1361,
1367,
1373,
1381,
1399,
1409,
1423,
1427,
1429,
1433,
1439,
1447,
1451,
1453,
1459,
1471,
1481,
1483,
1487,
1489,
1493,
1499,
1511,
1523,
1531,
1543,
1549,
1553,
1559,
1567,
1571,
1579,
1583,
1597
]
for (let i = 0; i < firstPrimes.length && (BigInt(firstPrimes[i]) <= w); i++) {
const p = BigInt(firstPrimes[i])
if (w === p) { return true } else if (w % p === _ZERO) { return false }
}
/*
1. Let a be the largest integer such that 2**a divides w1.
2. m = (w1) / 2**a.
3. wlen = len (w).
4. For i = 1 to iterations do
4.1 Obtain a string b of wlen bits from an RBG.
Comment: Ensure that 1 < b < w1.
4.2 If ((b 1) or (b w1)), then go to step 4.1.
4.3 z = b**m mod w.
4.4 If ((z = 1) or (z = w 1)), then go to step 4.7.
4.5 For j = 1 to a 1 do.
4.5.1 z = z**2 mod w.
4.5.2 If (z = w1), then go to step 4.7.
4.5.3 If (z = 1), then go to step 4.6.
4.6 Return COMPOSITE.
4.7 Continue.
Comment: Increment i for the do-loop in step 4.
5. Return PROBABLY PRIME.
*/
let a = _ZERO; let d = w - _ONE
while (d % _TWO === _ZERO) {
d /= _TWO
++a
}
const m = (w - _ONE) / (_TWO ** a)
/* eslint-disable no-labels */
loop: do {
const b = randBetween(w - _ONE, _TWO)
let z = modPow(b, m, w)
if (z === _ONE || z === w - _ONE) { continue }
for (let j = 1; j < a; j++) {
z = modPow(z, _TWO, w)
if (z === w - _ONE) { continue loop }
if (z === _ONE) { break }
}
return false
} while (--iterations)
/* eslint-enable no-labels */
return true
}
let _useWorkers = true // The following is just to check whether Node.js can use workers
{ // Node.js
_useWorkers = (function _workers () {
try {
require.resolve('worker_threads')
return true
} catch (e) {
console.log(`[bigint-crypto-utils] WARNING:
This node version doesn't support worker_threads. You should enable them in order to greatly speedup the generation of big prime numbers.
· With Node 11 it is enabled by default (consider upgrading).
· With Node 10, starting with 10.5.0, you can enable worker_threads at runtime executing node --experimental-worker `)
return false
}
})()
}
if (_useWorkers) { // node.js with support for workers
const { parentPort, isMainThread } = require('worker_threads')
if (!isMainThread) { // worker
parentPort.on('message', function (data) { // Let's start once we are called
// data = {rnd: <bigint>, iterations: <number>}
const isPrime = _isProbablyPrime(data.rnd, data.iterations)
parentPort.postMessage({
isPrime: isPrime,
value: data.rnd,
id: data.id
})
})
}
}
exports.abs = abs
exports.bitLength = bitLength
exports.eGcd = eGcd
exports.gcd = gcd
exports.isProbablyPrime = isProbablyPrime
exports.lcm = lcm
exports.max = max
exports.min = min
exports.modInv = modInv
exports.modPow = modPow
exports.prime = prime
exports.primeSync = primeSync
exports.randBetween = randBetween
exports.randBits = randBits
exports.randBytes = randBytes
exports.randBytesSync = randBytesSync
exports.toZn = toZn

1
node_modules/.bin/_mocha generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mocha/bin/_mocha

1
node_modules/.bin/acorn generated vendored Symbolic link
View File

@ -0,0 +1 @@
../acorn/bin/acorn

1
node_modules/.bin/eslint generated vendored Symbolic link
View File

@ -0,0 +1 @@
../eslint/bin/eslint.js

1
node_modules/.bin/esparse generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esparse.js

1
node_modules/.bin/esvalidate generated vendored Symbolic link
View File

@ -0,0 +1 @@
../esprima/bin/esvalidate.js

1
node_modules/.bin/flat generated vendored Symbolic link
View File

@ -0,0 +1 @@
../flat/cli.js

1
node_modules/.bin/handlebars generated vendored Symbolic link
View File

@ -0,0 +1 @@
../handlebars/bin/handlebars

1
node_modules/.bin/he generated vendored Symbolic link
View File

@ -0,0 +1 @@
../he/bin/he

1
node_modules/.bin/js-yaml generated vendored Symbolic link
View File

@ -0,0 +1 @@
../js-yaml/bin/js-yaml.js

1
node_modules/.bin/jsdoc generated vendored Symbolic link
View File

@ -0,0 +1 @@
../jsdoc/jsdoc.js

1
node_modules/.bin/jsdoc2md generated vendored Symbolic link
View File

@ -0,0 +1 @@
../jsdoc-to-markdown/bin/cli.js

1
node_modules/.bin/loose-envify generated vendored Symbolic link
View File

@ -0,0 +1 @@
../loose-envify/cli.js

1
node_modules/.bin/markdown-it generated vendored Symbolic link
View File

@ -0,0 +1 @@
../markdown-it/bin/markdown-it.js

1
node_modules/.bin/marked generated vendored Symbolic link
View File

@ -0,0 +1 @@
../marked/bin/marked

1
node_modules/.bin/mkdirp generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mkdirp/bin/cmd.js

1
node_modules/.bin/mocha generated vendored Symbolic link
View File

@ -0,0 +1 @@
../mocha/bin/mocha

1
node_modules/.bin/npm-run-all generated vendored Symbolic link
View File

@ -0,0 +1 @@
../npm-run-all/bin/npm-run-all/index.js

1
node_modules/.bin/parser generated vendored Symbolic link
View File

@ -0,0 +1 @@
../@babel/parser/bin/babel-parser.js

1
node_modules/.bin/pidtree generated vendored Symbolic link
View File

@ -0,0 +1 @@
../pidtree/bin/pidtree.js

1
node_modules/.bin/rimraf generated vendored Symbolic link
View File

@ -0,0 +1 @@
../rimraf/bin.js

1
node_modules/.bin/rollup generated vendored Symbolic link
View File

@ -0,0 +1 @@
../rollup/dist/bin/rollup

1
node_modules/.bin/run-p generated vendored Symbolic link
View File

@ -0,0 +1 @@
../npm-run-all/bin/run-p/index.js

1
node_modules/.bin/run-s generated vendored Symbolic link
View File

@ -0,0 +1 @@
../npm-run-all/bin/run-s/index.js

1
node_modules/.bin/semver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../semver/bin/semver

1
node_modules/.bin/standard generated vendored Symbolic link
View File

@ -0,0 +1 @@
../standard/bin/cmd.js

1
node_modules/.bin/terser generated vendored Symbolic link
View File

@ -0,0 +1 @@
../terser/bin/terser

1
node_modules/.bin/tsc generated vendored Symbolic link
View File

@ -0,0 +1 @@
../typescript/bin/tsc

1
node_modules/.bin/tsserver generated vendored Symbolic link
View File

@ -0,0 +1 @@
../typescript/bin/tsserver

1
node_modules/.bin/uglifyjs generated vendored Symbolic link
View File

@ -0,0 +1 @@
../uglify-js/bin/uglifyjs

1
node_modules/.bin/which generated vendored Symbolic link
View File

@ -0,0 +1 @@
../which/bin/which

22
node_modules/@babel/code-frame/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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.

19
node_modules/@babel/code-frame/README.md generated vendored Normal file
View File

@ -0,0 +1,19 @@
# @babel/code-frame
> Generate errors that contain a code frame that point to source locations.
See our website [@babel/code-frame](https://babeljs.io/docs/en/next/babel-code-frame.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/code-frame
```
or using yarn:
```sh
yarn add @babel/code-frame --dev
```

167
node_modules/@babel/code-frame/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,167 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.codeFrameColumns = codeFrameColumns;
exports.default = _default;
var _highlight = _interopRequireWildcard(require("@babel/highlight"));
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
let deprecationWarningShown = false;
function getDefs(chalk) {
return {
gutter: chalk.grey,
marker: chalk.red.bold,
message: chalk.red.bold
};
}
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
function getMarkerLines(loc, source, opts) {
const startLoc = Object.assign({
column: 0,
line: -1
}, loc.start);
const endLoc = Object.assign({}, startLoc, {}, loc.end);
const {
linesAbove = 2,
linesBelow = 3
} = opts || {};
const startLine = startLoc.line;
const startColumn = startLoc.column;
const endLine = endLoc.line;
const endColumn = endLoc.column;
let start = Math.max(startLine - (linesAbove + 1), 0);
let end = Math.min(source.length, endLine + linesBelow);
if (startLine === -1) {
start = 0;
}
if (endLine === -1) {
end = source.length;
}
const lineDiff = endLine - startLine;
const markerLines = {};
if (lineDiff) {
for (let i = 0; i <= lineDiff; i++) {
const lineNumber = i + startLine;
if (!startColumn) {
markerLines[lineNumber] = true;
} else if (i === 0) {
const sourceLength = source[lineNumber - 1].length;
markerLines[lineNumber] = [startColumn, sourceLength - startColumn + 1];
} else if (i === lineDiff) {
markerLines[lineNumber] = [0, endColumn];
} else {
const sourceLength = source[lineNumber - i].length;
markerLines[lineNumber] = [0, sourceLength];
}
}
} else {
if (startColumn === endColumn) {
if (startColumn) {
markerLines[startLine] = [startColumn, 0];
} else {
markerLines[startLine] = true;
}
} else {
markerLines[startLine] = [startColumn, endColumn - startColumn];
}
}
return {
start,
end,
markerLines
};
}
function codeFrameColumns(rawLines, loc, opts = {}) {
const highlighted = (opts.highlightCode || opts.forceColor) && (0, _highlight.shouldHighlight)(opts);
const chalk = (0, _highlight.getChalk)(opts);
const defs = getDefs(chalk);
const maybeHighlight = (chalkFn, string) => {
return highlighted ? chalkFn(string) : string;
};
const lines = rawLines.split(NEWLINE);
const {
start,
end,
markerLines
} = getMarkerLines(loc, lines, opts);
const hasColumns = loc.start && typeof loc.start.column === "number";
const numberMaxWidth = String(end).length;
const highlightedLines = highlighted ? (0, _highlight.default)(rawLines, opts) : rawLines;
let frame = highlightedLines.split(NEWLINE).slice(start, end).map((line, index) => {
const number = start + 1 + index;
const paddedNumber = ` ${number}`.slice(-numberMaxWidth);
const gutter = ` ${paddedNumber} | `;
const hasMarker = markerLines[number];
const lastMarkerLine = !markerLines[number + 1];
if (hasMarker) {
let markerLine = "";
if (Array.isArray(hasMarker)) {
const markerSpacing = line.slice(0, Math.max(hasMarker[0] - 1, 0)).replace(/[^\t]/g, " ");
const numberOfMarkers = hasMarker[1] || 1;
markerLine = ["\n ", maybeHighlight(defs.gutter, gutter.replace(/\d/g, " ")), markerSpacing, maybeHighlight(defs.marker, "^").repeat(numberOfMarkers)].join("");
if (lastMarkerLine && opts.message) {
markerLine += " " + maybeHighlight(defs.message, opts.message);
}
}
return [maybeHighlight(defs.marker, ">"), maybeHighlight(defs.gutter, gutter), line, markerLine].join("");
} else {
return ` ${maybeHighlight(defs.gutter, gutter)}${line}`;
}
}).join("\n");
if (opts.message && !hasColumns) {
frame = `${" ".repeat(numberMaxWidth + 1)}${opts.message}\n${frame}`;
}
if (highlighted) {
return chalk.reset(frame);
} else {
return frame;
}
}
function _default(rawLines, lineNumber, colNumber, opts = {}) {
if (!deprecationWarningShown) {
deprecationWarningShown = true;
const message = "Passing lineNumber and colNumber is deprecated to @babel/code-frame. Please use `codeFrameColumns`.";
if (process.emitWarning) {
process.emitWarning(message, "DeprecationWarning");
} else {
const deprecationError = new Error(message);
deprecationError.name = "DeprecationWarning";
console.warn(new Error(message));
}
}
colNumber = Math.max(colNumber, 0);
const location = {
start: {
column: colNumber,
line: lineNumber
}
};
return codeFrameColumns(rawLines, location, opts);
}

54
node_modules/@babel/code-frame/package.json generated vendored Normal file
View File

@ -0,0 +1,54 @@
{
"_from": "@babel/code-frame@^7.5.5",
"_id": "@babel/code-frame@7.8.3",
"_inBundle": false,
"_integrity": "sha512-a9gxpmdXtZEInkCSHUJDLHZVBgb1QS0jhss4cPP93EW7s+uC5bikET2twEF3KV+7rDblJcmNvTR7VJejqd2C2g==",
"_location": "/@babel/code-frame",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/code-frame@^7.5.5",
"name": "@babel/code-frame",
"escapedName": "@babel%2fcode-frame",
"scope": "@babel",
"rawSpec": "^7.5.5",
"saveSpec": null,
"fetchSpec": "^7.5.5"
},
"_requiredBy": [
"/eslint",
"/rollup-plugin-terser"
],
"_resolved": "https://registry.npmjs.org/@babel/code-frame/-/code-frame-7.8.3.tgz",
"_shasum": "33e25903d7481181534e12ec0a25f16b6fcf419e",
"_spec": "@babel/code-frame@^7.5.5",
"_where": "/home/juan/bigint-crypto-utils/node_modules/rollup-plugin-terser",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/highlight": "^7.8.3"
},
"deprecated": false,
"description": "Generate errors that contain a code frame that point to source locations.",
"devDependencies": {
"chalk": "^2.0.0",
"strip-ansi": "^4.0.0"
},
"gitHead": "a7620bd266ae1345975767bbc7abf09034437017",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/code-frame",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-code-frame"
},
"version": "7.8.3"
}

View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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.

View File

@ -0,0 +1,19 @@
# @babel/helper-validator-identifier
> Validate identifier/keywords name
See our website [@babel/helper-validator-identifier](https://babeljs.io/docs/en/next/babel-helper-validator-identifier.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/helper-validator-identifier
```
or using yarn:
```sh
yarn add @babel/helper-validator-identifier --dev
```

View File

@ -0,0 +1,77 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isIdentifierStart = isIdentifierStart;
exports.isIdentifierChar = isIdentifierChar;
exports.isIdentifierName = isIdentifierName;
let nonASCIIidentifierStartChars = "\xaa\xb5\xba\xc0-\xd6\xd8-\xf6\xf8-\u02c1\u02c6-\u02d1\u02e0-\u02e4\u02ec\u02ee\u0370-\u0374\u0376\u0377\u037a-\u037d\u037f\u0386\u0388-\u038a\u038c\u038e-\u03a1\u03a3-\u03f5\u03f7-\u0481\u048a-\u052f\u0531-\u0556\u0559\u0560-\u0588\u05d0-\u05ea\u05ef-\u05f2\u0620-\u064a\u066e\u066f\u0671-\u06d3\u06d5\u06e5\u06e6\u06ee\u06ef\u06fa-\u06fc\u06ff\u0710\u0712-\u072f\u074d-\u07a5\u07b1\u07ca-\u07ea\u07f4\u07f5\u07fa\u0800-\u0815\u081a\u0824\u0828\u0840-\u0858\u0860-\u086a\u08a0-\u08b4\u08b6-\u08c7\u0904-\u0939\u093d\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098c\u098f\u0990\u0993-\u09a8\u09aa-\u09b0\u09b2\u09b6-\u09b9\u09bd\u09ce\u09dc\u09dd\u09df-\u09e1\u09f0\u09f1\u09fc\u0a05-\u0a0a\u0a0f\u0a10\u0a13-\u0a28\u0a2a-\u0a30\u0a32\u0a33\u0a35\u0a36\u0a38\u0a39\u0a59-\u0a5c\u0a5e\u0a72-\u0a74\u0a85-\u0a8d\u0a8f-\u0a91\u0a93-\u0aa8\u0aaa-\u0ab0\u0ab2\u0ab3\u0ab5-\u0ab9\u0abd\u0ad0\u0ae0\u0ae1\u0af9\u0b05-\u0b0c\u0b0f\u0b10\u0b13-\u0b28\u0b2a-\u0b30\u0b32\u0b33\u0b35-\u0b39\u0b3d\u0b5c\u0b5d\u0b5f-\u0b61\u0b71\u0b83\u0b85-\u0b8a\u0b8e-\u0b90\u0b92-\u0b95\u0b99\u0b9a\u0b9c\u0b9e\u0b9f\u0ba3\u0ba4\u0ba8-\u0baa\u0bae-\u0bb9\u0bd0\u0c05-\u0c0c\u0c0e-\u0c10\u0c12-\u0c28\u0c2a-\u0c39\u0c3d\u0c58-\u0c5a\u0c60\u0c61\u0c80\u0c85-\u0c8c\u0c8e-\u0c90\u0c92-\u0ca8\u0caa-\u0cb3\u0cb5-\u0cb9\u0cbd\u0cde\u0ce0\u0ce1\u0cf1\u0cf2\u0d04-\u0d0c\u0d0e-\u0d10\u0d12-\u0d3a\u0d3d\u0d4e\u0d54-\u0d56\u0d5f-\u0d61\u0d7a-\u0d7f\u0d85-\u0d96\u0d9a-\u0db1\u0db3-\u0dbb\u0dbd\u0dc0-\u0dc6\u0e01-\u0e30\u0e32\u0e33\u0e40-\u0e46\u0e81\u0e82\u0e84\u0e86-\u0e8a\u0e8c-\u0ea3\u0ea5\u0ea7-\u0eb0\u0eb2\u0eb3\u0ebd\u0ec0-\u0ec4\u0ec6\u0edc-\u0edf\u0f00\u0f40-\u0f47\u0f49-\u0f6c\u0f88-\u0f8c\u1000-\u102a\u103f\u1050-\u1055\u105a-\u105d\u1061\u1065\u1066\u106e-\u1070\u1075-\u1081\u108e\u10a0-\u10c5\u10c7\u10cd\u10d0-\u10fa\u10fc-\u1248\u124a-\u124d\u1250-\u1256\u1258\u125a-\u125d\u1260-\u1288\u128a-\u128d\u1290-\u12b0\u12b2-\u12b5\u12b8-\u12be\u12c0\u12c2-\u12c5\u12c8-\u12d6\u12d8-\u1310\u1312-\u1315\u1318-\u135a\u1380-\u138f\u13a0-\u13f5\u13f8-\u13fd\u1401-\u166c\u166f-\u167f\u1681-\u169a\u16a0-\u16ea\u16ee-\u16f8\u1700-\u170c\u170e-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176c\u176e-\u1770\u1780-\u17b3\u17d7\u17dc\u1820-\u1878\u1880-\u18a8\u18aa\u18b0-\u18f5\u1900-\u191e\u1950-\u196d\u1970-\u1974\u1980-\u19ab\u19b0-\u19c9\u1a00-\u1a16\u1a20-\u1a54\u1aa7\u1b05-\u1b33\u1b45-\u1b4b\u1b83-\u1ba0\u1bae\u1baf\u1bba-\u1be5\u1c00-\u1c23\u1c4d-\u1c4f\u1c5a-\u1c7d\u1c80-\u1c88\u1c90-\u1cba\u1cbd-\u1cbf\u1ce9-\u1cec\u1cee-\u1cf3\u1cf5\u1cf6\u1cfa\u1d00-\u1dbf\u1e00-\u1f15\u1f18-\u1f1d\u1f20-\u1f45\u1f48-\u1f4d\u1f50-\u1f57\u1f59\u1f5b\u1f5d\u1f5f-\u1f7d\u1f80-\u1fb4\u1fb6-\u1fbc\u1fbe\u1fc2-\u1fc4\u1fc6-\u1fcc\u1fd0-\u1fd3\u1fd6-\u1fdb\u1fe0-\u1fec\u1ff2-\u1ff4\u1ff6-\u1ffc\u2071\u207f\u2090-\u209c\u2102\u2107\u210a-\u2113\u2115\u2118-\u211d\u2124\u2126\u2128\u212a-\u2139\u213c-\u213f\u2145-\u2149\u214e\u2160-\u2188\u2c00-\u2c2e\u2c30-\u2c5e\u2c60-\u2ce4\u2ceb-\u2cee\u2cf2\u2cf3\u2d00-\u2d25\u2d27\u2d2d\u2d30-\u2d67\u2d6f\u2d80-\u2d96\u2da0-\u2da6\u2da8-\u2dae\u2db0-\u2db6\u2db8-\u2dbe\u2dc0-\u2dc6\u2dc8-\u2dce\u2dd0-\u2dd6\u2dd8-\u2dde\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303c\u3041-\u3096\u309b-\u309f\u30a1-\u30fa\u30fc-\u30ff\u3105-\u312f\u3131-\u318e\u31a0-\u31bf\u31f0-\u31ff\u3400-\u4dbf\u4e00-\u9ffc\ua000-\ua48c\ua4d0-\ua4fd\ua500-\ua60c\ua610-\ua61f\ua62a\ua62b\ua640-\ua66e\ua67f-\ua69d\ua6a0-\ua6ef\ua717-\ua71f\ua722-\ua788\ua78b-\ua7bf\ua7c2-\ua7ca\ua7f5-\ua801\ua803-\ua805\ua807-\ua80a\ua80c-\ua822\ua840-\ua873\ua882-\ua8b3\ua8f2-\ua8f7\ua8fb\ua8fd\ua8fe\ua90a-\ua925\ua930-\ua946\ua960-\ua97c\ua984-\ua9b2\ua9cf\ua9e0-\ua9e4\ua9e6-\ua9ef\ua9fa-\ua9fe\uaa00-\uaa28\uaa40-\uaa42\uaa44-\uaa4b\uaa60-\uaa76\uaa7a\uaa7e-\uaaaf\uaab1\uaab5\uaab6\uaab9-\uaabd\uaac0\uaac2\uaadb-\uaadd\uaae0-\uaaea\uaaf2-\uaaf4\uab01-\uab06\uab09-\uab0e\uab11-\uab16\uab20-\uab26\uab28-\uab2e\uab30-\uab5a\uab5c-\uab69\uab70-\uabe2\uac00-\ud7a3\ud7b0-\ud7c6\ud7cb-\ud7fb\uf900-\ufa6d\ufa70-\ufad9\ufb00-\ufb06\ufb13-\ufb17\ufb1d\ufb1f-\ufb28\ufb2a-\ufb36\ufb38-\ufb3c\ufb3e\ufb40\ufb41\ufb43\ufb44\ufb46-\ufbb1\ufbd3-\ufd3d\ufd50-\ufd8f\ufd92-\ufdc7\ufdf0-\ufdfb\ufe70-\ufe74\ufe76-\ufefc\uff21-\uff3a\uff41-\uff5a\uff66-\uffbe\uffc2-\uffc7\uffca-\uffcf\uffd2-\uffd7\uffda-\uffdc";
let nonASCIIidentifierChars = "\u200c\u200d\xb7\u0300-\u036f\u0387\u0483-\u0487\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u0669\u0670\u06d6-\u06dc\u06df-\u06e4\u06e7\u06e8\u06ea-\u06ed\u06f0-\u06f9\u0711\u0730-\u074a\u07a6-\u07b0\u07c0-\u07c9\u07eb-\u07f3\u07fd\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0859-\u085b\u08d3-\u08e1\u08e3-\u0903\u093a-\u093c\u093e-\u094f\u0951-\u0957\u0962\u0963\u0966-\u096f\u0981-\u0983\u09bc\u09be-\u09c4\u09c7\u09c8\u09cb-\u09cd\u09d7\u09e2\u09e3\u09e6-\u09ef\u09fe\u0a01-\u0a03\u0a3c\u0a3e-\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a66-\u0a71\u0a75\u0a81-\u0a83\u0abc\u0abe-\u0ac5\u0ac7-\u0ac9\u0acb-\u0acd\u0ae2\u0ae3\u0ae6-\u0aef\u0afa-\u0aff\u0b01-\u0b03\u0b3c\u0b3e-\u0b44\u0b47\u0b48\u0b4b-\u0b4d\u0b55-\u0b57\u0b62\u0b63\u0b66-\u0b6f\u0b82\u0bbe-\u0bc2\u0bc6-\u0bc8\u0bca-\u0bcd\u0bd7\u0be6-\u0bef\u0c00-\u0c04\u0c3e-\u0c44\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0c66-\u0c6f\u0c81-\u0c83\u0cbc\u0cbe-\u0cc4\u0cc6-\u0cc8\u0cca-\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0ce6-\u0cef\u0d00-\u0d03\u0d3b\u0d3c\u0d3e-\u0d44\u0d46-\u0d48\u0d4a-\u0d4d\u0d57\u0d62\u0d63\u0d66-\u0d6f\u0d81-\u0d83\u0dca\u0dcf-\u0dd4\u0dd6\u0dd8-\u0ddf\u0de6-\u0def\u0df2\u0df3\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0e50-\u0e59\u0eb1\u0eb4-\u0ebc\u0ec8-\u0ecd\u0ed0-\u0ed9\u0f18\u0f19\u0f20-\u0f29\u0f35\u0f37\u0f39\u0f3e\u0f3f\u0f71-\u0f84\u0f86\u0f87\u0f8d-\u0f97\u0f99-\u0fbc\u0fc6\u102b-\u103e\u1040-\u1049\u1056-\u1059\u105e-\u1060\u1062-\u1064\u1067-\u106d\u1071-\u1074\u1082-\u108d\u108f-\u109d\u135d-\u135f\u1369-\u1371\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b4-\u17d3\u17dd\u17e0-\u17e9\u180b-\u180d\u1810-\u1819\u18a9\u1920-\u192b\u1930-\u193b\u1946-\u194f\u19d0-\u19da\u1a17-\u1a1b\u1a55-\u1a5e\u1a60-\u1a7c\u1a7f-\u1a89\u1a90-\u1a99\u1ab0-\u1abd\u1abf\u1ac0\u1b00-\u1b04\u1b34-\u1b44\u1b50-\u1b59\u1b6b-\u1b73\u1b80-\u1b82\u1ba1-\u1bad\u1bb0-\u1bb9\u1be6-\u1bf3\u1c24-\u1c37\u1c40-\u1c49\u1c50-\u1c59\u1cd0-\u1cd2\u1cd4-\u1ce8\u1ced\u1cf4\u1cf7-\u1cf9\u1dc0-\u1df9\u1dfb-\u1dff\u203f\u2040\u2054\u20d0-\u20dc\u20e1\u20e5-\u20f0\u2cef-\u2cf1\u2d7f\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua620-\ua629\ua66f\ua674-\ua67d\ua69e\ua69f\ua6f0\ua6f1\ua802\ua806\ua80b\ua823-\ua827\ua82c\ua880\ua881\ua8b4-\ua8c5\ua8d0-\ua8d9\ua8e0-\ua8f1\ua8ff-\ua909\ua926-\ua92d\ua947-\ua953\ua980-\ua983\ua9b3-\ua9c0\ua9d0-\ua9d9\ua9e5\ua9f0-\ua9f9\uaa29-\uaa36\uaa43\uaa4c\uaa4d\uaa50-\uaa59\uaa7b-\uaa7d\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uaaeb-\uaaef\uaaf5\uaaf6\uabe3-\uabea\uabec\uabed\uabf0-\uabf9\ufb1e\ufe00-\ufe0f\ufe20-\ufe2f\ufe33\ufe34\ufe4d-\ufe4f\uff10-\uff19\uff3f";
const nonASCIIidentifierStart = new RegExp("[" + nonASCIIidentifierStartChars + "]");
const nonASCIIidentifier = new RegExp("[" + nonASCIIidentifierStartChars + nonASCIIidentifierChars + "]");
nonASCIIidentifierStartChars = nonASCIIidentifierChars = null;
const astralIdentifierStartCodes = [0, 11, 2, 25, 2, 18, 2, 1, 2, 14, 3, 13, 35, 122, 70, 52, 268, 28, 4, 48, 48, 31, 14, 29, 6, 37, 11, 29, 3, 35, 5, 7, 2, 4, 43, 157, 19, 35, 5, 35, 5, 39, 9, 51, 157, 310, 10, 21, 11, 7, 153, 5, 3, 0, 2, 43, 2, 1, 4, 0, 3, 22, 11, 22, 10, 30, 66, 18, 2, 1, 11, 21, 11, 25, 71, 55, 7, 1, 65, 0, 16, 3, 2, 2, 2, 28, 43, 28, 4, 28, 36, 7, 2, 27, 28, 53, 11, 21, 11, 18, 14, 17, 111, 72, 56, 50, 14, 50, 14, 35, 349, 41, 7, 1, 79, 28, 11, 0, 9, 21, 107, 20, 28, 22, 13, 52, 76, 44, 33, 24, 27, 35, 30, 0, 3, 0, 9, 34, 4, 0, 13, 47, 15, 3, 22, 0, 2, 0, 36, 17, 2, 24, 85, 6, 2, 0, 2, 3, 2, 14, 2, 9, 8, 46, 39, 7, 3, 1, 3, 21, 2, 6, 2, 1, 2, 4, 4, 0, 19, 0, 13, 4, 159, 52, 19, 3, 21, 2, 31, 47, 21, 1, 2, 0, 185, 46, 42, 3, 37, 47, 21, 0, 60, 42, 14, 0, 72, 26, 230, 43, 117, 63, 32, 7, 3, 0, 3, 7, 2, 1, 2, 23, 16, 0, 2, 0, 95, 7, 3, 38, 17, 0, 2, 0, 29, 0, 11, 39, 8, 0, 22, 0, 12, 45, 20, 0, 35, 56, 264, 8, 2, 36, 18, 0, 50, 29, 113, 6, 2, 1, 2, 37, 22, 0, 26, 5, 2, 1, 2, 31, 15, 0, 328, 18, 190, 0, 80, 921, 103, 110, 18, 195, 2749, 1070, 4050, 582, 8634, 568, 8, 30, 114, 29, 19, 47, 17, 3, 32, 20, 6, 18, 689, 63, 129, 74, 6, 0, 67, 12, 65, 1, 2, 0, 29, 6135, 9, 1237, 43, 8, 8952, 286, 50, 2, 18, 3, 9, 395, 2309, 106, 6, 12, 4, 8, 8, 9, 5991, 84, 2, 70, 2, 1, 3, 0, 3, 1, 3, 3, 2, 11, 2, 0, 2, 6, 2, 64, 2, 3, 3, 7, 2, 6, 2, 27, 2, 3, 2, 4, 2, 0, 4, 6, 2, 339, 3, 24, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 30, 2, 24, 2, 7, 2357, 44, 11, 6, 17, 0, 370, 43, 1301, 196, 60, 67, 8, 0, 1205, 3, 2, 26, 2, 1, 2, 0, 3, 0, 2, 9, 2, 3, 2, 0, 2, 0, 7, 0, 5, 0, 2, 0, 2, 0, 2, 2, 2, 1, 2, 0, 3, 0, 2, 0, 2, 0, 2, 0, 2, 0, 2, 1, 2, 0, 3, 3, 2, 6, 2, 3, 2, 3, 2, 0, 2, 9, 2, 16, 6, 2, 2, 4, 2, 16, 4421, 42717, 35, 4148, 12, 221, 3, 5761, 15, 7472, 3104, 541, 1507, 4938];
const astralIdentifierCodes = [509, 0, 227, 0, 150, 4, 294, 9, 1368, 2, 2, 1, 6, 3, 41, 2, 5, 0, 166, 1, 574, 3, 9, 9, 370, 1, 154, 10, 176, 2, 54, 14, 32, 9, 16, 3, 46, 10, 54, 9, 7, 2, 37, 13, 2, 9, 6, 1, 45, 0, 13, 2, 49, 13, 9, 3, 2, 11, 83, 11, 7, 0, 161, 11, 6, 9, 7, 3, 56, 1, 2, 6, 3, 1, 3, 2, 10, 0, 11, 1, 3, 6, 4, 4, 193, 17, 10, 9, 5, 0, 82, 19, 13, 9, 214, 6, 3, 8, 28, 1, 83, 16, 16, 9, 82, 12, 9, 9, 84, 14, 5, 9, 243, 14, 166, 9, 71, 5, 2, 1, 3, 3, 2, 0, 2, 1, 13, 9, 120, 6, 3, 6, 4, 0, 29, 9, 41, 6, 2, 3, 9, 0, 10, 10, 47, 15, 406, 7, 2, 7, 17, 9, 57, 21, 2, 13, 123, 5, 4, 0, 2, 1, 2, 6, 2, 0, 9, 9, 49, 4, 2, 1, 2, 4, 9, 9, 330, 3, 19306, 9, 135, 4, 60, 6, 26, 9, 1014, 0, 2, 54, 8, 3, 82, 0, 12, 1, 19628, 1, 5319, 4, 4, 5, 9, 7, 3, 6, 31, 3, 149, 2, 1418, 49, 513, 54, 5, 49, 9, 0, 15, 0, 23, 4, 2, 14, 1361, 6, 2, 16, 3, 6, 2, 1, 2, 4, 262, 6, 10, 9, 419, 13, 1495, 6, 110, 6, 6, 9, 4759, 9, 787719, 239];
function isInAstralSet(code, set) {
let pos = 0x10000;
for (let i = 0, length = set.length; i < length; i += 2) {
pos += set[i];
if (pos > code) return false;
pos += set[i + 1];
if (pos >= code) return true;
}
return false;
}
function isIdentifierStart(code) {
if (code < 65) return code === 36;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifierStart.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes);
}
function isIdentifierChar(code) {
if (code < 48) return code === 36;
if (code < 58) return true;
if (code < 65) return false;
if (code <= 90) return true;
if (code < 97) return code === 95;
if (code <= 122) return true;
if (code <= 0xffff) {
return code >= 0xaa && nonASCIIidentifier.test(String.fromCharCode(code));
}
return isInAstralSet(code, astralIdentifierStartCodes) || isInAstralSet(code, astralIdentifierCodes);
}
function isIdentifierName(name) {
let isFirst = true;
for (let _i = 0, _Array$from = Array.from(name); _i < _Array$from.length; _i++) {
const char = _Array$from[_i];
const cp = char.codePointAt(0);
if (isFirst) {
if (!isIdentifierStart(cp)) {
return false;
}
isFirst = false;
} else if (!isIdentifierChar(cp)) {
return false;
}
}
return true;
}

View File

@ -0,0 +1,57 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
Object.defineProperty(exports, "isIdentifierName", {
enumerable: true,
get: function () {
return _identifier.isIdentifierName;
}
});
Object.defineProperty(exports, "isIdentifierChar", {
enumerable: true,
get: function () {
return _identifier.isIdentifierChar;
}
});
Object.defineProperty(exports, "isIdentifierStart", {
enumerable: true,
get: function () {
return _identifier.isIdentifierStart;
}
});
Object.defineProperty(exports, "isReservedWord", {
enumerable: true,
get: function () {
return _keyword.isReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindOnlyReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindOnlyReservedWord;
}
});
Object.defineProperty(exports, "isStrictBindReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictBindReservedWord;
}
});
Object.defineProperty(exports, "isStrictReservedWord", {
enumerable: true,
get: function () {
return _keyword.isStrictReservedWord;
}
});
Object.defineProperty(exports, "isKeyword", {
enumerable: true,
get: function () {
return _keyword.isKeyword;
}
});
var _identifier = require("./identifier");
var _keyword = require("./keyword");

View File

@ -0,0 +1,38 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.isReservedWord = isReservedWord;
exports.isStrictReservedWord = isStrictReservedWord;
exports.isStrictBindOnlyReservedWord = isStrictBindOnlyReservedWord;
exports.isStrictBindReservedWord = isStrictBindReservedWord;
exports.isKeyword = isKeyword;
const reservedWords = {
keyword: ["break", "case", "catch", "continue", "debugger", "default", "do", "else", "finally", "for", "function", "if", "return", "switch", "throw", "try", "var", "const", "while", "with", "new", "this", "super", "class", "extends", "export", "import", "null", "true", "false", "in", "instanceof", "typeof", "void", "delete"],
strict: ["implements", "interface", "let", "package", "private", "protected", "public", "static", "yield"],
strictBind: ["eval", "arguments"]
};
const keywords = new Set(reservedWords.keyword);
const reservedWordsStrictSet = new Set(reservedWords.strict);
const reservedWordsStrictBindSet = new Set(reservedWords.strictBind);
function isReservedWord(word, inModule) {
return inModule && word === "await" || word === "enum";
}
function isStrictReservedWord(word, inModule) {
return isReservedWord(word, inModule) || reservedWordsStrictSet.has(word);
}
function isStrictBindOnlyReservedWord(word) {
return reservedWordsStrictBindSet.has(word);
}
function isStrictBindReservedWord(word, inModule) {
return isStrictReservedWord(word, inModule) || isStrictBindOnlyReservedWord(word);
}
function isKeyword(word) {
return keywords.has(word);
}

View File

@ -0,0 +1,46 @@
{
"_from": "@babel/helper-validator-identifier@^7.9.0",
"_id": "@babel/helper-validator-identifier@7.9.0",
"_inBundle": false,
"_integrity": "sha512-6G8bQKjOh+of4PV/ThDm/rRqlU7+IGoJuofpagU5GlEl29Vv0RGqqt86ZGRV8ZuSOY3o+8yXl5y782SMcG7SHw==",
"_location": "/@babel/helper-validator-identifier",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/helper-validator-identifier@^7.9.0",
"name": "@babel/helper-validator-identifier",
"escapedName": "@babel%2fhelper-validator-identifier",
"scope": "@babel",
"rawSpec": "^7.9.0",
"saveSpec": null,
"fetchSpec": "^7.9.0"
},
"_requiredBy": [
"/@babel/highlight"
],
"_resolved": "https://registry.npmjs.org/@babel/helper-validator-identifier/-/helper-validator-identifier-7.9.0.tgz",
"_shasum": "ad53562a7fc29b3b9a91bbf7d10397fd146346ed",
"_spec": "@babel/helper-validator-identifier@^7.9.0",
"_where": "/home/juan/bigint-crypto-utils/node_modules/@babel/highlight",
"bundleDependencies": false,
"deprecated": false,
"description": "Validate identifier/keywords name",
"devDependencies": {
"charcodes": "^0.2.0",
"unicode-13.0.0": "^0.8.0"
},
"exports": "./lib/index.js",
"gitHead": "8d5e422be27251cfaadf8dd2536b31b4a5024b02",
"license": "MIT",
"main": "./lib/index.js",
"name": "@babel/helper-validator-identifier",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-helper-validator-identifier"
},
"version": "7.9.0"
}

View File

@ -0,0 +1,75 @@
"use strict";
// Always use the latest available version of Unicode!
// https://tc39.github.io/ecma262/#sec-conformance
const version = "13.0.0";
const start = require("unicode-" +
version +
"/Binary_Property/ID_Start/code-points.js").filter(function(ch) {
return ch > 0x7f;
});
let last = -1;
const cont = [0x200c, 0x200d].concat(
require("unicode-" +
version +
"/Binary_Property/ID_Continue/code-points.js").filter(function(ch) {
return ch > 0x7f && search(start, ch, last + 1) == -1;
})
);
function search(arr, ch, starting) {
for (let i = starting; arr[i] <= ch && i < arr.length; last = i++) {
if (arr[i] === ch) return i;
}
return -1;
}
function pad(str, width) {
while (str.length < width) str = "0" + str;
return str;
}
function esc(code) {
const hex = code.toString(16);
if (hex.length <= 2) return "\\x" + pad(hex, 2);
else return "\\u" + pad(hex, 4);
}
function generate(chars) {
const astral = [];
let re = "";
for (let i = 0, at = 0x10000; i < chars.length; i++) {
const from = chars[i];
let to = from;
while (i < chars.length - 1 && chars[i + 1] == to + 1) {
i++;
to++;
}
if (to <= 0xffff) {
if (from == to) re += esc(from);
else if (from + 1 == to) re += esc(from) + esc(to);
else re += esc(from) + "-" + esc(to);
} else {
astral.push(from - at, to - from);
at = to;
}
}
return { nonASCII: re, astral: astral };
}
const startData = generate(start);
const contData = generate(cont);
console.log("/* prettier-ignore */");
console.log('let nonASCIIidentifierStartChars = "' + startData.nonASCII + '";');
console.log("/* prettier-ignore */");
console.log('let nonASCIIidentifierChars = "' + contData.nonASCII + '";');
console.log("/* prettier-ignore */");
console.log(
"const astralIdentifierStartCodes = " + JSON.stringify(startData.astral) + ";"
);
console.log("/* prettier-ignore */");
console.log(
"const astralIdentifierCodes = " + JSON.stringify(contData.astral) + ";"
);

22
node_modules/@babel/highlight/LICENSE generated vendored Normal file
View File

@ -0,0 +1,22 @@
MIT License
Copyright (c) 2014-present Sebastian McKenzie and other contributors
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.

19
node_modules/@babel/highlight/README.md generated vendored Normal file
View File

@ -0,0 +1,19 @@
# @babel/highlight
> Syntax highlight JavaScript strings for output in terminals.
See our website [@babel/highlight](https://babeljs.io/docs/en/next/babel-highlight.html) for more information.
## Install
Using npm:
```sh
npm install --save-dev @babel/highlight
```
or using yarn:
```sh
yarn add @babel/highlight --dev
```

107
node_modules/@babel/highlight/lib/index.js generated vendored Normal file
View File

@ -0,0 +1,107 @@
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.shouldHighlight = shouldHighlight;
exports.getChalk = getChalk;
exports.default = highlight;
var _jsTokens = _interopRequireWildcard(require("js-tokens"));
var _helperValidatorIdentifier = require("@babel/helper-validator-identifier");
var _chalk = _interopRequireDefault(require("chalk"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function () { return cache; }; return cache; }
function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || typeof obj !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }
function getDefs(chalk) {
return {
keyword: chalk.cyan,
capitalized: chalk.yellow,
jsx_tag: chalk.yellow,
punctuator: chalk.yellow,
number: chalk.magenta,
string: chalk.green,
regex: chalk.magenta,
comment: chalk.grey,
invalid: chalk.white.bgRed.bold
};
}
const NEWLINE = /\r\n|[\n\r\u2028\u2029]/;
const JSX_TAG = /^[a-z][\w-]*$/i;
const BRACKET = /^[()[\]{}]$/;
function getTokenType(match) {
const [offset, text] = match.slice(-2);
const token = (0, _jsTokens.matchToToken)(match);
if (token.type === "name") {
if ((0, _helperValidatorIdentifier.isKeyword)(token.value) || (0, _helperValidatorIdentifier.isReservedWord)(token.value)) {
return "keyword";
}
if (JSX_TAG.test(token.value) && (text[offset - 1] === "<" || text.substr(offset - 2, 2) == "</")) {
return "jsx_tag";
}
if (token.value[0] !== token.value[0].toLowerCase()) {
return "capitalized";
}
}
if (token.type === "punctuator" && BRACKET.test(token.value)) {
return "bracket";
}
if (token.type === "invalid" && (token.value === "@" || token.value === "#")) {
return "punctuator";
}
return token.type;
}
function highlightTokens(defs, text) {
return text.replace(_jsTokens.default, function (...args) {
const type = getTokenType(args);
const colorize = defs[type];
if (colorize) {
return args[0].split(NEWLINE).map(str => colorize(str)).join("\n");
} else {
return args[0];
}
});
}
function shouldHighlight(options) {
return _chalk.default.supportsColor || options.forceColor;
}
function getChalk(options) {
let chalk = _chalk.default;
if (options.forceColor) {
chalk = new _chalk.default.constructor({
enabled: true,
level: 1
});
}
return chalk;
}
function highlight(code, options = {}) {
if (shouldHighlight(options)) {
const chalk = getChalk(options);
const defs = getDefs(chalk);
return highlightTokens(defs, code);
} else {
return code;
}
}

54
node_modules/@babel/highlight/package.json generated vendored Normal file
View File

@ -0,0 +1,54 @@
{
"_from": "@babel/highlight@^7.8.3",
"_id": "@babel/highlight@7.9.0",
"_inBundle": false,
"_integrity": "sha512-lJZPilxX7Op3Nv/2cvFdnlepPXDxi29wxteT57Q965oc5R9v86ztx0jfxVrTcBk8C2kcPkkDa2Z4T3ZsPPVWsQ==",
"_location": "/@babel/highlight",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/highlight@^7.8.3",
"name": "@babel/highlight",
"escapedName": "@babel%2fhighlight",
"scope": "@babel",
"rawSpec": "^7.8.3",
"saveSpec": null,
"fetchSpec": "^7.8.3"
},
"_requiredBy": [
"/@babel/code-frame"
],
"_resolved": "https://registry.npmjs.org/@babel/highlight/-/highlight-7.9.0.tgz",
"_shasum": "4e9b45ccb82b79607271b2979ad82c7b68163079",
"_spec": "@babel/highlight@^7.8.3",
"_where": "/home/juan/bigint-crypto-utils/node_modules/@babel/code-frame",
"author": {
"name": "suchipi",
"email": "me@suchipi.com"
},
"bundleDependencies": false,
"dependencies": {
"@babel/helper-validator-identifier": "^7.9.0",
"chalk": "^2.0.0",
"js-tokens": "^4.0.0"
},
"deprecated": false,
"description": "Syntax highlight JavaScript strings for output in terminals.",
"devDependencies": {
"strip-ansi": "^4.0.0"
},
"gitHead": "8d5e422be27251cfaadf8dd2536b31b4a5024b02",
"homepage": "https://babeljs.io/",
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/highlight",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-highlight"
},
"version": "7.9.0"
}

1073
node_modules/@babel/parser/CHANGELOG.md generated vendored Normal file

File diff suppressed because it is too large Load Diff

19
node_modules/@babel/parser/LICENSE generated vendored Normal file
View File

@ -0,0 +1,19 @@
Copyright (C) 2012-2014 by various contributors (see AUTHORS)
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.

19
node_modules/@babel/parser/README.md generated vendored Normal file
View File

@ -0,0 +1,19 @@
# @babel/parser
> A JavaScript parser
See our website [@babel/parser](https://babeljs.io/docs/en/next/babel-parser.html) for more information or the [issues](https://github.com/babel/babel/issues?utf8=%E2%9C%93&q=is%3Aissue+label%3A%22pkg%3A+parser+%28babylon%29%22+is%3Aopen) associated with this package.
## Install
Using npm:
```sh
npm install --save-dev @babel/parser
```
or using yarn:
```sh
yarn add @babel/parser --dev
```

15
node_modules/@babel/parser/bin/babel-parser.js generated vendored Executable file
View File

@ -0,0 +1,15 @@
#!/usr/bin/env node
/* eslint no-var: 0 */
var parser = require("..");
var fs = require("fs");
var filename = process.argv[2];
if (!filename) {
console.error("no filename specified");
} else {
var file = fs.readFileSync(filename, "utf8");
var ast = parser.parse(file);
console.log(JSON.stringify(ast, null, " "));
}

12736
node_modules/@babel/parser/lib/index.js generated vendored Normal file

File diff suppressed because it is too large Load Diff

1
node_modules/@babel/parser/lib/index.js.map generated vendored Normal file

File diff suppressed because one or more lines are too long

72
node_modules/@babel/parser/package.json generated vendored Normal file
View File

@ -0,0 +1,72 @@
{
"_from": "@babel/parser@^7.4.4",
"_id": "@babel/parser@7.9.4",
"_inBundle": false,
"_integrity": "sha512-bC49otXX6N0/VYhgOMh4gnP26E9xnDZK3TmbNpxYzzz9BQLBosQwfyOe9/cXUU3txYhTzLCbcqd5c8y/OmCjHA==",
"_location": "/@babel/parser",
"_phantomChildren": {},
"_requested": {
"type": "range",
"registry": true,
"raw": "@babel/parser@^7.4.4",
"name": "@babel/parser",
"escapedName": "@babel%2fparser",
"scope": "@babel",
"rawSpec": "^7.4.4",
"saveSpec": null,
"fetchSpec": "^7.4.4"
},
"_requiredBy": [
"/jsdoc"
],
"_resolved": "https://registry.npmjs.org/@babel/parser/-/parser-7.9.4.tgz",
"_shasum": "68a35e6b0319bbc014465be43828300113f2f2e8",
"_spec": "@babel/parser@^7.4.4",
"_where": "/home/juan/bigint-crypto-utils/node_modules/jsdoc",
"author": {
"name": "Sebastian McKenzie",
"email": "sebmck@gmail.com"
},
"bin": {
"parser": "bin/babel-parser.js"
},
"bundleDependencies": false,
"deprecated": false,
"description": "A JavaScript parser",
"devDependencies": {
"@babel/code-frame": "^7.8.3",
"@babel/helper-fixtures": "^7.8.6",
"@babel/helper-validator-identifier": "^7.9.0",
"charcodes": "^0.2.0"
},
"engines": {
"node": ">=6.0.0"
},
"files": [
"bin",
"lib",
"typings"
],
"gitHead": "d3cf5fb5f4b46a1f7e9e33f2d24a466e3ea1e50f",
"homepage": "https://babeljs.io/",
"keywords": [
"babel",
"javascript",
"parser",
"tc39",
"ecmascript",
"@babel/parser"
],
"license": "MIT",
"main": "lib/index.js",
"name": "@babel/parser",
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "https://github.com/babel/babel/tree/master/packages/babel-parser"
},
"types": "typings/babel-parser.d.ts",
"version": "7.9.4"
}

146
node_modules/@babel/parser/typings/babel-parser.d.ts generated vendored Normal file
View File

@ -0,0 +1,146 @@
// Type definitions for @babel/parser
// Project: https://github.com/babel/babel/tree/master/packages/babel-parser
// Definitions by: Troy Gerwien <https://github.com/yortus>
// Marvin Hagemeister <https://github.com/marvinhagemeister>
// Avi Vahl <https://github.com/AviVahl>
// TypeScript Version: 2.9
/**
* Parse the provided code as an entire ECMAScript program.
*/
export function parse(input: string, options?: ParserOptions): import('@babel/types').File;
/**
* Parse the provided code as a single expression.
*/
export function parseExpression(input: string, options?: ParserOptions): import('@babel/types').Expression;
export interface ParserOptions {
/**
* By default, import and export declarations can only appear at a program's top level.
* Setting this option to true allows them anywhere where a statement is allowed.
*/
allowImportExportEverywhere?: boolean;
/**
* By default, await use is not allowed outside of an async function.
* Set this to true to accept such code.
*/
allowAwaitOutsideFunction?: boolean;
/**
* By default, a return statement at the top level raises an error.
* Set this to true to accept such code.
*/
allowReturnOutsideFunction?: boolean;
allowSuperOutsideMethod?: boolean;
/**
* By default, exported identifiers must refer to a declared variable.
* Set this to true to allow export statements to reference undeclared variables.
*/
allowUndeclaredExports?: boolean;
/**
* Indicate the mode the code should be parsed in.
* Can be one of "script", "module", or "unambiguous". Defaults to "script".
* "unambiguous" will make @babel/parser attempt to guess, based on the presence
* of ES6 import or export statements.
* Files with ES6 imports and exports are considered "module" and are otherwise "script".
*/
sourceType?: 'script' | 'module' | 'unambiguous';
/**
* Correlate output AST nodes with their source filename.
* Useful when generating code and source maps from the ASTs of multiple input files.
*/
sourceFilename?: string;
/**
* By default, the first line of code parsed is treated as line 1.
* You can provide a line number to alternatively start with.
* Useful for integration with other source tools.
*/
startLine?: number;
/**
* Array containing the plugins that you want to enable.
*/
plugins?: ParserPlugin[];
/**
* Should the parser work in strict mode.
* Defaults to true if sourceType === 'module'. Otherwise, false.
*/
strictMode?: boolean;
/**
* Adds a ranges property to each node: [node.start, node.end]
*/
ranges?: boolean;
/**
* Adds all parsed tokens to a tokens property on the File node.
*/
tokens?: boolean;
/**
* By default, the parser adds information about parentheses by setting
* `extra.parenthesized` to `true` as needed.
* When this option is `true` the parser creates `ParenthesizedExpression`
* AST nodes instead of using the `extra` property.
*/
createParenthesizedExpressions?: boolean;
}
export type ParserPlugin =
'asyncGenerators' |
'bigInt' |
'classPrivateMethods' |
'classPrivateProperties' |
'classProperties' |
'decorators' |
'decorators-legacy' |
'doExpressions' |
'dynamicImport' |
'estree' |
'exportDefaultFrom' |
'exportNamespaceFrom' | // deprecated
'flow' |
'flowComments' |
'functionBind' |
'functionSent' |
'importMeta' |
'jsx' |
'logicalAssignment' |
'nullishCoalescingOperator' |
'numericSeparator' |
'objectRestSpread' |
'optionalCatchBinding' |
'optionalChaining' |
'partialApplication' |
'pipelineOperator' |
'placeholders' |
'throwExpressions' |
'topLevelAwait' |
'typescript' |
'v8intrinsic' |
ParserPluginWithOptions;
export type ParserPluginWithOptions =
['decorators', DecoratorsPluginOptions] |
['pipelineOperator', PipelineOperatorPluginOptions] |
['flow', FlowPluginOptions];
export interface DecoratorsPluginOptions {
decoratorsBeforeExport?: boolean;
}
export interface PipelineOperatorPluginOptions {
proposal: 'minimal' | 'smart';
}
export interface FlowPluginOptions {
all?: boolean;
}

374
node_modules/@rollup/plugin-commonjs/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,374 @@
# @rollup/plugin-commonjs ChangeLog
## v11.0.2
_2020-02-01_
### Updates
- docs: fix link for plugin-node-resolve (#170)
- chore: update dependencies (5405eea)
- chore: remove jsnext:main (#152)
## v11.0.1
_2020-01-04_
### Bugfixes
- fix: module.exports object spread (#121)
## 11.0.0
_2019-12-13_
- **Breaking:** Minimum compatible Rollup version is 1.20.0
- **Breaking:** Minimum supported Node version is 8.0.0
- Published as @rollup/plugin-commonjs
## 10.1.0
_2019-08-27_
- Normalize ids before looking up in named export map ([#406](https://github.com/rollup/rollup-plugin-commonjs/issues/406))
- Update README.md with note on symlinks ([#405](https://github.com/rollup/rollup-plugin-commonjs/issues/405))
## 10.0.2
_2019-08-03_
- Support preserveSymlinks: false ([#401](https://github.com/rollup/rollup-plugin-commonjs/issues/401))
## 10.0.1
_2019-06-27_
- Make tests run with Node 6 again and update dependencies ([#389](https://github.com/rollup/rollup-plugin-commonjs/issues/389))
- Handle builtins appropriately for resolve 1.11.0 ([#395](https://github.com/rollup/rollup-plugin-commonjs/issues/395))
## 10.0.0
_2019-05-15_
- Use new Rollup@1.12 context functions, fix issue when resolveId returns an object ([#387](https://github.com/rollup/rollup-plugin-commonjs/issues/387))
## 9.3.4
_2019-04-04_
- Make "extensions" optional ([#384](https://github.com/rollup/rollup-plugin-commonjs/issues/384))
- Use same typing for include and exclude properties ([#385](https://github.com/rollup/rollup-plugin-commonjs/issues/385))
## 9.3.3
_2019-04-04_
- Remove colon from module prefixes ([#371](https://github.com/rollup/rollup-plugin-commonjs/issues/371))
## 9.3.2
_2019-04-04_
- Use shared extractAssignedNames, fix destructuring issue ([#303](https://github.com/rollup/rollup-plugin-commonjs/issues/303))
## 9.3.1
_2019-04-04_
- Include typings in release ([#382](https://github.com/rollup/rollup-plugin-commonjs/issues/382))
## 9.3.0
_2019-04-03_
- Add TypeScript types ([#363](https://github.com/rollup/rollup-plugin-commonjs/issues/363))
## 9.2.3
_2019-04-02_
- Improve support for ES3 browsers ([#364](https://github.com/rollup/rollup-plugin-commonjs/issues/364))
- Add note about monorepo usage to readme ([#372](https://github.com/rollup/rollup-plugin-commonjs/issues/372))
- Add .js extension to generated helper file ([#373](https://github.com/rollup/rollup-plugin-commonjs/issues/373))
## 9.2.2
_2019-03-25_
- Handle array destructuring assignment ([#379](https://github.com/rollup/rollup-plugin-commonjs/issues/379))
## 9.2.1
_2019-02-23_
- Use correct context when manually resolving ids ([#370](https://github.com/rollup/rollup-plugin-commonjs/issues/370))
## 9.2.0
_2018-10-10_
- Fix missing default warning, produce better code when importing known ESM default exports ([#349](https://github.com/rollup/rollup-plugin-commonjs/issues/349))
- Refactor code and add prettier ([#346](https://github.com/rollup/rollup-plugin-commonjs/issues/346))
## 9.1.8
_2018-09-18_
- Ignore virtual modules created by other plugins ([#327](https://github.com/rollup/rollup-plugin-commonjs/issues/327))
- Add "location" and "process" to reserved words ([#330](https://github.com/rollup/rollup-plugin-commonjs/issues/330))
## 9.1.6
_2018-08-24_
- Keep commonJS detection between instantiations ([#338](https://github.com/rollup/rollup-plugin-commonjs/issues/338))
## 9.1.5
_2018-08-09_
- Handle object form of input ([#329](https://github.com/rollup/rollup-plugin-commonjs/issues/329))
## 9.1.4
_2018-07-27_
- Make "from" a reserved word ([#320](https://github.com/rollup/rollup-plugin-commonjs/issues/320))
## 9.1.3
_2018-04-30_
- Fix a caching issue ([#316](https://github.com/rollup/rollup-plugin-commonjs/issues/316))
## 9.1.2
_2018-04-30_
- Re-publication of 9.1.0
## 9.1.1
_2018-04-30_
- Fix ordering of modules when using rollup 0.58 ([#302](https://github.com/rollup/rollup-plugin-commonjs/issues/302))
## 9.1.0
- Do not automatically wrap modules with return statements in top level arrow functions ([#302](https://github.com/rollup/rollup-plugin-commonjs/issues/302))
## 9.0.0
- Make rollup a peer dependency with a version range ([#300](https://github.com/rollup/rollup-plugin-commonjs/issues/300))
## 8.4.1
- Re-release of 8.3.0 as #287 was actually a breaking change
## 8.4.0
- Better handle non-CJS files that contain CJS keywords ([#285](https://github.com/rollup/rollup-plugin-commonjs/issues/285))
- Use rollup's plugin context`parse` function ([#287](https://github.com/rollup/rollup-plugin-commonjs/issues/287))
- Improve error handling ([#288](https://github.com/rollup/rollup-plugin-commonjs/issues/288))
## 8.3.0
- Handle multiple entry points ([#283](https://github.com/rollup/rollup-plugin-commonjs/issues/283))
- Extract named exports from exported object literals ([#272](https://github.com/rollup/rollup-plugin-commonjs/issues/272))
- Fix when `options.external` is modified by other plugins ([#264](https://github.com/rollup/rollup-plugin-commonjs/issues/264))
- Recognize static template strings in require statements ([#271](https://github.com/rollup/rollup-plugin-commonjs/issues/271))
## 8.2.4
- Don't import default from ES modules that don't export default ([#206](https://github.com/rollup/rollup-plugin-commonjs/issues/206))
## 8.2.3
- Prevent duplicate default exports ([#230](https://github.com/rollup/rollup-plugin-commonjs/pull/230))
- Only include default export when it exists ([#226](https://github.com/rollup/rollup-plugin-commonjs/pull/226))
- Deconflict `require` aliases ([#232](https://github.com/rollup/rollup-plugin-commonjs/issues/232))
## 8.2.1
- Fix magic-string deprecation warning
## 8.2.0
- Avoid using `index` as a variable name ([#208](https://github.com/rollup/rollup-plugin-commonjs/pull/208))
## 8.1.1
- Compatibility with 0.48 ([#220](https://github.com/rollup/rollup-plugin-commonjs/issues/220))
## 8.1.0
- Handle `options.external` correctly ([#212](https://github.com/rollup/rollup-plugin-commonjs/pull/212))
- Support top-level return ([#195](https://github.com/rollup/rollup-plugin-commonjs/pull/195))
## 8.0.2
- Fix another `var` rewrite bug ([#181](https://github.com/rollup/rollup-plugin-commonjs/issues/181))
## 8.0.1
- Remove declarators within a var declaration correctly ([#179](https://github.com/rollup/rollup-plugin-commonjs/issues/179))
## 8.0.0
- Prefer the names dependencies are imported by for the common `var foo = require('foo')` pattern ([#176](https://github.com/rollup/rollup-plugin-commonjs/issues/176))
## 7.1.0
- Allow certain `require` statements to pass through unmolested ([#174](https://github.com/rollup/rollup-plugin-commonjs/issues/174))
## 7.0.2
- Handle duplicate default exports ([#158](https://github.com/rollup/rollup-plugin-commonjs/issues/158))
## 7.0.1
- Fix exports with parentheses ([#168](https://github.com/rollup/rollup-plugin-commonjs/issues/168))
## 7.0.0
- Rewrite `typeof module`, `typeof module.exports` and `typeof exports` as `'object'` ([#151](https://github.com/rollup/rollup-plugin-commonjs/issues/151))
## 6.0.1
- Don't overwrite globals ([#127](https://github.com/rollup/rollup-plugin-commonjs/issues/127))
## 6.0.0
- Rewrite top-level `define` as `undefined`, so AMD-first UMD blocks do not cause breakage ([#144](https://github.com/rollup/rollup-plugin-commonjs/issues/144))
- Support ES2017 syntax ([#132](https://github.com/rollup/rollup-plugin-commonjs/issues/132))
- Deconflict exported reserved keywords ([#116](https://github.com/rollup/rollup-plugin-commonjs/issues/116))
## 5.0.5
- Fix parenthesis wrapped exports ([#120](https://github.com/rollup/rollup-plugin-commonjs/issues/120))
## 5.0.4
- Ensure named exports are added to default export in optimised modules ([#112](https://github.com/rollup/rollup-plugin-commonjs/issues/112))
## 5.0.3
- Respect custom `namedExports` in optimised modules ([#35](https://github.com/rollup/rollup-plugin-commonjs/issues/35))
## 5.0.2
- Replace `require` (outside call expressions) with `commonjsRequire` helper ([#77](https://github.com/rollup/rollup-plugin-commonjs/issues/77), [#83](https://github.com/rollup/rollup-plugin-commonjs/issues/83))
## 5.0.1
- Deconflict against globals ([#84](https://github.com/rollup/rollup-plugin-commonjs/issues/84))
## 5.0.0
- Optimise modules that don't need to be wrapped in a function ([#106](https://github.com/rollup/rollup-plugin-commonjs/pull/106))
- Ignore modules containing `import` and `export` statements ([#96](https://github.com/rollup/rollup-plugin-commonjs/pull/96))
## 4.1.0
- Ignore dead branches ([#93](https://github.com/rollup/rollup-plugin-commonjs/issues/93))
## 4.0.1
- Fix `ignoreGlobal` option ([#86](https://github.com/rollup/rollup-plugin-commonjs/pull/86))
## 4.0.0
- Better interop and smaller output ([#92](https://github.com/rollup/rollup-plugin-commonjs/pull/92))
## 3.3.1
- Deconflict export and local module ([rollup/rollup#554](https://github.com/rollup/rollup/issues/554))
## 3.3.0
- Keep the order of execution for require calls ([#43](https://github.com/rollup/rollup-plugin-commonjs/pull/43))
- Use interopDefault as helper ([#42](https://github.com/rollup/rollup-plugin-commonjs/issues/42))
## 3.2.0
- Use named exports as a function when no default export is defined ([#524](https://github.com/rollup/rollup/issues/524))
## 3.1.0
- Replace `typeof require` with `'function'` ([#38](https://github.com/rollup/rollup-plugin-commonjs/issues/38))
- Don't attempt to resolve entry file relative to importer ([#63](https://github.com/rollup/rollup-plugin-commonjs/issues/63))
## 3.0.2
- Handle multiple references to `global`
## 3.0.1
- Return a `name`
## 3.0.0
- Make `transform` stateless ([#71](https://github.com/rollup/rollup-plugin-commonjs/pull/71))
- Support web worker `global` ([#50](https://github.com/rollup/rollup-plugin-commonjs/issues/50))
- Ignore global with `options.ignoreGlobal` ([#48](https://github.com/rollup/rollup-plugin-commonjs/issues/48))
## 2.2.1
- Prevent false positives with `namedExports` ([#36](https://github.com/rollup/rollup-plugin-commonjs/issues/36))
## 2.2.0
- Rewrite top-level `this` expressions to mean the same as `global` ([#31](https://github.com/rollup/rollup-plugin-commonjs/issues/31))
## 2.1.0
- Optimised module wrappers ([#20](https://github.com/rollup/rollup-plugin-commonjs/pull/20))
- Allow control over named exports via `options.namedExports` ([#18](https://github.com/rollup/rollup-plugin-commonjs/issues/18))
- Handle bare imports correctly ([#23](https://github.com/rollup/rollup-plugin-commonjs/issues/23))
- Blacklist all reserved words as export names ([#21](https://github.com/rollup/rollup-plugin-commonjs/issues/21))
- Configure allowed file extensions via `options.extensions` ([#27](https://github.com/rollup/rollup-plugin-commonjs/pull/27))
## 2.0.0
- Support for transpiled modules `exports.default` is used as the default export in place of `module.exports`, if applicable, and `__esModule` is not exported ([#16](https://github.com/rollup/rollup-plugin-commonjs/pull/16))
## 1.4.0
- Generate sourcemaps by default
## 1.3.0
- Handle references to `global` ([#6](https://github.com/rollup/rollup-plugin-commonjs/issues/6))
## 1.2.0
- Generate named exports where possible ([#5](https://github.com/rollup/rollup-plugin-commonjs/issues/5))
- Handle shadowed `require`/`module`/`exports`
## 1.1.0
- Handle dots in filenames ([#3](https://github.com/rollup/rollup-plugin-commonjs/issues/3))
- Wrap modules in IIFE for more readable output
## 1.0.0
- Stable release, now that Rollup supports plugins
## 0.2.1
- Allow mixed CommonJS/ES6 imports/exports
- Use `var` instead of `let`
## 0.2.0
- Sourcemap support
- Support `options.include` and `options.exclude`
- Bail early if module is obviously not a CommonJS module
## 0.1.1
Add dist files to package (whoops!)
## 0.1.0
- First release

21
node_modules/@rollup/plugin-commonjs/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
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.

172
node_modules/@rollup/plugin-commonjs/README.md generated vendored Normal file
View File

@ -0,0 +1,172 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-commonjs
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-commonjs
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-commonjs
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-commonjs
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-commonjs
🍣 A Rollup plugin to convert CommonJS modules to ES6, so they can be included in a Rollup bundle
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```bash
npm install @rollup/plugin-commonjs --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [commonjs()]
};
```
Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
## Options
### `exclude`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default non-CommonJS modules are ignored.
### `include`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default CommonJS modules are targeted.
### `extensions`
Type: `Array[...String]`<br>
Default: `['.js']`
Search for extensions other than .js in the order specified.
### `ignoreGlobal`
Type: `Boolean`<br>
Default: `false`
If true, uses of `global` won't be dealt with by this plugin.
### `sourceMap`
Type: `Boolean`<br>
Default: `true`
If false, skips source map generation for CommonJS modules.
### `namedExports`
Type: `Object`<br>
Default: `null`
Explicitly specify unresolvable named exports.
This plugin will attempt to create named exports, where appropriate, so you can do this...
```js
// importer.js
import { named } from './exporter.js';
// exporter.js
module.exports = { named: 42 }; // or `exports.named = 42;`
```
...but that's not always possible:
```js
// importer.js
import { named } from 'my-lib';
// my-lib.js
var myLib = exports;
myLib.named = "you can't see me";
```
In those cases, you can specify custom named exports:
```js
commonjs({
namedExports: {
// left-hand side can be an absolute path, a path
// relative to the current directory, or the name
// of a module in node_modules
'my-lib': ['named']
}
});
```
### `ignore`
Type: `Array[...String | (String) => Boolean]`<br>
Default: `[]`
Sometimes you have to leave require statements unconverted. Pass an array containing the IDs or an `id => boolean` function. Only use this option if you know what you're doing!
## Using with @rollup/plugin-node-resolve
Since most CommonJS packages you are importing are probably depdenencies in `node_modules`, you may need to use [@rollup/plugin-node-resolve](https://github.com/rollup/plugins/tree/master/packages/node-resolve):
```js
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'main.js',
output: {
file: 'bundle.js',
format: 'iife',
name: 'MyModule'
},
plugins: [resolve(), commonjs()]
};
```
## Usage with symlinks
Symlinks are common in monorepos and are also created by the `npm link` command. Rollup with `@rollup/plugin-node-resolve` resolves modules to their real paths by default. So `include` and `exclude` paths should handle real paths rather than symlinked paths (e.g. `../common/node_modules/**` instead of `node_modules/**`). You may also use a regular expression for `include` that works regardless of base path. Try this:
```js
commonjs({
include: /node_modules/
});
```
Whether symlinked module paths are [realpathed](http://man7.org/linux/man-pages/man3/realpath.3.html) or preserved depends on Rollup's `preserveSymlinks` setting, which is false by default, matching Node.js' default behavior. Setting `preserveSymlinks` to true in your Rollup config will cause `import` and `export` to match based on symlinked paths instead.
## Strict mode
ES modules are _always_ parsed in strict mode. That means that certain non-strict constructs (like octal literals) will be treated as syntax errors when Rollup parses modules that use them. Some older CommonJS modules depend on those constructs, and if you depend on them your bundle will blow up. There's basically nothing we can do about that.
Luckily, there is absolutely no good reason _not_ to use strict mode for everything — so the solution to this problem is to lobby the authors of those modules to update them.
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

893
node_modules/@rollup/plugin-commonjs/dist/index.es.js generated vendored Normal file
View File

@ -0,0 +1,893 @@
import { statSync, existsSync, realpathSync } from 'fs';
import { resolve, dirname, sep, basename, extname, normalize } from 'path';
import { isCore, sync } from 'resolve';
import { makeLegalIdentifier, attachScopes, extractAssignedNames, createFilter } from '@rollup/pluginutils';
import { walk } from 'estree-walker';
import MagicString from 'magic-string';
import isReference from 'is-reference';
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
return;
}
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
var peerDependencies = {
rollup: "^1.20.0"
};
const PROXY_SUFFIX = '?commonjs-proxy';
const getProxyId = id => `\0${id}${PROXY_SUFFIX}`;
const getIdFromProxyId = proxyId => proxyId.slice(1, -PROXY_SUFFIX.length);
const EXTERNAL_SUFFIX = '?commonjs-external';
const getExternalProxyId = id => `\0${id}${EXTERNAL_SUFFIX}`;
const getIdFromExternalProxyId = proxyId => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
const HELPERS_ID = '\0commonjsHelpers.js'; // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
const HELPERS = `
export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
export function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
export function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
export function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
export function getCjsExportFromNamespace (n) {
return n && n['default'] || n;
}`;
/* eslint-disable no-undefined */
const isCjsPromises = new Map();
function getIsCjsPromise(id) {
let isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) return isCjsPromise.promise;
const promise = new Promise(resolve => {
isCjsPromise = {
resolve,
promise: undefined
};
isCjsPromises.set(id, isCjsPromise);
});
isCjsPromise.promise = promise;
return promise;
}
function setIsCjsPromise(id, resolution) {
const isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) {
if (isCjsPromise.resolve) {
isCjsPromise.resolve(resolution);
isCjsPromise.resolve = undefined;
}
} else {
isCjsPromises.set(id, {
promise: Promise.resolve(resolution),
resolve: undefined
});
}
}
/* eslint-disable no-param-reassign, no-undefined */
function getCandidatesForExtension(resolved, extension) {
return [resolved + extension, `${resolved}${sep}index${extension}`];
}
function getCandidates(resolved, extensions) {
return extensions.reduce((paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), [resolved]);
}
function getResolveId(extensions) {
function resolveExtensions(importee, importer) {
// not our problem
if (importee[0] !== '.' || !importer) return undefined;
const resolved = resolve(dirname(importer), importee);
const candidates = getCandidates(resolved, extensions);
for (let i = 0; i < candidates.length; i += 1) {
try {
const stats = statSync(candidates[i]);
if (stats.isFile()) return {
id: candidates[i]
};
} catch (err) {
/* noop */
}
}
return undefined;
}
function resolveId(importee, importer) {
const isProxyModule = importee.endsWith(PROXY_SUFFIX);
if (isProxyModule) {
importee = getIdFromProxyId(importee);
} else if (importee.startsWith('\0')) {
if (importee === HELPERS_ID) {
return importee;
}
return null;
}
if (importer && importer.endsWith(PROXY_SUFFIX)) {
importer = getIdFromProxyId(importer);
}
return this.resolve(importee, importer, {
skipSelf: true
}).then(resolved => {
if (!resolved) {
resolved = resolveExtensions(importee, importer);
}
if (isProxyModule) {
if (!resolved) {
return {
id: getExternalProxyId(importee),
external: false
};
}
resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
resolved.external = false;
return resolved;
}
return resolved;
});
}
return resolveId;
}
/* eslint-disable no-undefined */
const operators = {
'==': x => equals(x.left, x.right, false),
'!=': x => not(operators['=='](x)),
'===': x => equals(x.left, x.right, true),
'!==': x => not(operators['==='](x)),
'!': x => isFalsy(x.argument),
'&&': x => isTruthy(x.left) && isTruthy(x.right),
'||': x => isTruthy(x.left) || isTruthy(x.right)
};
function flatten(node) {
const parts = [];
while (node.type === 'MemberExpression') {
if (node.computed) return null;
parts.unshift(node.property.name); // eslint-disable-next-line no-param-reassign
node = node.object;
}
if (node.type !== 'Identifier') return null;
const _node = node,
name = _node.name;
parts.unshift(name);
return {
name,
keypath: parts.join('.')
};
}
function isTruthy(node) {
if (node.type === 'Literal') return !!node.value;
if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
if (node.operator in operators) return operators[node.operator](node);
return undefined;
}
function isFalsy(node) {
return not(isTruthy(node));
}
function not(value) {
return value === undefined ? value : !value;
}
function equals(a, b, strict) {
if (a.type !== b.type) return undefined; // eslint-disable-next-line eqeqeq
if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
return undefined;
}
/* eslint-disable import/prefer-default-export */
function getName(id) {
const name = makeLegalIdentifier(basename(id, extname(id)));
if (name !== 'index') {
return name;
}
const segments = dirname(id).split(sep);
return makeLegalIdentifier(segments[segments.length - 1]);
}
const reserved = 'process location abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for from function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split(' ');
const blacklist = {
__esModule: true
};
reserved.forEach(word => blacklist[word] = true);
const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
const importExportDeclaration = /^(?:Import|Export(?:Named|Default))Declaration/;
const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
function deconflict(scope, globals, identifier) {
let i = 1;
let deconflicted = identifier;
while (scope.contains(deconflicted) || globals.has(deconflicted) || deconflicted in blacklist) {
deconflicted = `${identifier}_${i}`;
i += 1;
}
scope.declarations[deconflicted] = true;
return deconflicted;
}
function tryParse(parse, code, id) {
try {
return parse(code, {
allowReturnOutsideFunction: true
});
} catch (err) {
err.message += ` in ${id}`;
throw err;
}
}
function hasCjsKeywords(code, ignoreGlobal) {
const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
return firstpass.test(code);
}
function checkEsModule(parse, code, id) {
const ast = tryParse(parse, code, id);
let isEsModule = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = ast.body[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const node = _step.value;
if (node.type === 'ExportDefaultDeclaration') return {
isEsModule: true,
hasDefaultExport: true,
ast
};
if (node.type === 'ExportNamedDeclaration') {
isEsModule = true;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = node.specifiers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
const specifier = _step2.value;
if (specifier.exported.name === 'default') {
return {
isEsModule: true,
hasDefaultExport: true,
ast
};
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
} else if (importExportDeclaration.test(node.type)) isEsModule = true;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return {
isEsModule,
hasDefaultExport: false,
ast
};
}
function transformCommonjs(parse, code, id, isEntry, ignoreGlobal, ignoreRequire, customNamedExports, sourceMap, allowDynamicRequire, astCache) {
const ast = astCache || tryParse(parse, code, id);
const magicString = new MagicString(code);
const required = {}; // Because objects have no guaranteed ordering, yet we need it,
// we need to keep track of the order in a array
const sources = [];
let uid = 0;
let scope = attachScopes(ast, 'scope');
const uses = {
module: false,
exports: false,
global: false,
require: false
};
let lexicalDepth = 0;
let programDepth = 0;
const globals = new Set(); // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
const namedExports = {}; // TODO handle transpiled modules
let shouldWrap = /__esModule/.test(code);
function isRequireStatement(node) {
if (!node) return false;
if (node.type !== 'CallExpression') return false;
if (node.callee.name !== 'require' || scope.contains('require')) return false; // Weird case of require() without arguments
if (node.arguments.length === 0) return false;
return true;
}
function hasDynamicArguments(node) {
return node.arguments.length > 1 || node.arguments[0].type !== 'Literal' && (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0);
}
function isStaticRequireStatement(node) {
if (!isRequireStatement(node)) return false;
if (hasDynamicArguments(node)) return false;
if (ignoreRequire(node.arguments[0].value)) return false;
return true;
}
function getRequireStringArg(node) {
return node.arguments[0].type === 'Literal' ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked;
}
function getRequired(node, name) {
const sourceId = getRequireStringArg(node);
const existing = required[sourceId]; // eslint-disable-next-line no-undefined
if (existing === undefined) {
if (!name) {
do {
name = `require$$${uid}`;
uid += 1;
} while (scope.contains(name));
}
sources.push(sourceId);
required[sourceId] = {
source: sourceId,
name,
importsDefault: false
};
}
return required[sourceId];
} // do a first pass, see which names are assigned to. This is necessary to prevent
// illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
// where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
const assignedTo = new Set();
walk(ast, {
enter(node) {
if (node.type !== 'AssignmentExpression') return;
if (node.left.type === 'MemberExpression') return;
extractAssignedNames(node.left).forEach(name => {
assignedTo.add(name);
});
}
});
walk(ast, {
enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
} // skip dead branches
if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
if (node === parent.consequent && isFalsy(parent.test)) {
this.skip();
return;
}
if (node === parent.alternate && isTruthy(parent.test)) {
this.skip();
return;
}
}
if (node._skip) {
this.skip();
return;
}
programDepth += 1;
if (node.scope) {
scope = node.scope;
}
if (functionType.test(node.type)) lexicalDepth += 1; // if toplevel return, we need to wrap it
if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
shouldWrap = true;
} // rewrite `this` as `commonjsHelpers.commonjsGlobal`
if (node.type === 'ThisExpression' && lexicalDepth === 0) {
uses.global = true;
if (!ignoreGlobal) magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
return;
} // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
const flattened = flatten(node.argument);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
if (flattened.keypath === 'module.exports' || flattened.keypath === 'module' || flattened.keypath === 'exports') {
magicString.overwrite(node.start, node.end, `'object'`, {
storeName: false
});
}
} // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
// `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
if (node.type === 'Identifier') {
if (isReference(node, parent) && !scope.contains(node.name)) {
if (node.name in uses) {
if (node.name === 'require') {
if (allowDynamicRequire) return;
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
}
uses[node.name] = true;
if (node.name === 'global' && !ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
} // if module or exports are used outside the context of an assignment
// expression, we need to wrap the module
if (node.name === 'module' || node.name === 'exports') {
shouldWrap = true;
}
}
if (node.name === 'define') {
magicString.overwrite(node.start, node.end, 'undefined', {
storeName: true
});
}
globals.add(node.name);
}
return;
} // Is this an assignment to exports or module.exports?
if (node.type === 'AssignmentExpression') {
if (node.left.type !== 'MemberExpression') return;
const flattened = flatten(node.left);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
const match = exportsPattern.exec(flattened.keypath);
if (!match || flattened.keypath === 'exports') return;
uses[flattened.name] = true; // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...`
// if this isn't top-level, we'll need to wrap the module
if (programDepth > 3) shouldWrap = true;
node.left._skip = true;
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
node.right.properties.forEach(prop => {
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
const name = prop.key.name;
if (name === makeLegalIdentifier(name)) namedExports[name] = true;
});
return;
}
if (match[1]) namedExports[match[1]] = true;
return;
} // if this is `var x = require('x')`, we can do `import x from 'x'`
if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && isStaticRequireStatement(node.init)) {
// for now, only do this for top-level requires. maybe fix this in future
if (scope.parent) return; // edge case — CJS allows you to assign to imports. ES doesn't
if (assignedTo.has(node.id.name)) return;
const required = getRequired(node.init, node.id.name);
required.importsDefault = true;
if (required.name === node.id.name) {
node._shouldRemove = true;
}
}
if (!isStaticRequireStatement(node)) return;
const required = getRequired(node);
if (parent.type === 'ExpressionStatement') {
// is a bare import, e.g. `require('foo');`
magicString.remove(parent.start, parent.end);
} else {
required.importsDefault = true;
magicString.overwrite(node.start, node.end, required.name);
}
node.callee._skip = true;
},
leave(node) {
programDepth -= 1;
if (node.scope) scope = scope.parent;
if (functionType.test(node.type)) lexicalDepth -= 1;
if (node.type === 'VariableDeclaration') {
let keepDeclaration = false;
let c = node.declarations[0].start;
for (let i = 0; i < node.declarations.length; i += 1) {
const declarator = node.declarations[i];
if (declarator._shouldRemove) {
magicString.remove(c, declarator.end);
} else {
if (!keepDeclaration) {
magicString.remove(c, declarator.start);
keepDeclaration = true;
}
c = declarator.end;
}
}
if (!keepDeclaration) {
magicString.remove(node.start, node.end);
}
}
}
});
if (!sources.length && !uses.module && !uses.exports && !uses.require && (ignoreGlobal || !uses.global)) {
if (Object.keys(namedExports).length) {
throw new Error(`Custom named exports were specified for ${id} but it does not appear to be a CommonJS module`);
} // not a CommonJS module
return null;
}
const includeHelpers = shouldWrap || uses.global || uses.require;
const importBlock = `${(includeHelpers ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`] : []).concat(sources.map(source => // import the actual module before the proxy, so that we know
// what kind of proxy to build
`import '${source}';`), sources.map(source => {
const _required$source = required[source],
name = _required$source.name,
importsDefault = _required$source.importsDefault;
return `import ${importsDefault ? `${name} from ` : ``}'${getProxyId(source)}';`;
})).join('\n')}\n\n`;
const namedExportDeclarations = [];
let wrapperStart = '';
let wrapperEnd = '';
const moduleName = deconflict(scope, globals, getName(id));
if (!isEntry) {
const exportModuleExports = {
str: `export { ${moduleName} as __moduleExports };`,
name: '__moduleExports'
};
namedExportDeclarations.push(exportModuleExports);
}
const name = getName(id);
function addExport(x) {
const deconflicted = deconflict(scope, globals, name);
const declaration = deconflicted === name ? `export var ${x} = ${moduleName}.${x};` : `var ${deconflicted} = ${moduleName}.${x};\nexport { ${deconflicted} as ${x} };`;
namedExportDeclarations.push({
str: declaration,
name: x
});
}
if (customNamedExports) customNamedExports.forEach(addExport);
const defaultExportPropertyAssignments = [];
let hasDefaultExport = false;
if (shouldWrap) {
const args = `module${uses.exports ? ', exports' : ''}`;
wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
wrapperEnd = `\n});`;
} else {
const names = [];
ast.body.forEach(node => {
if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
const left = node.expression.left;
const flattened = flatten(left);
if (!flattened) return;
const match = exportsPattern.exec(flattened.keypath);
if (!match) return;
if (flattened.keypath === 'module.exports') {
hasDefaultExport = true;
magicString.overwrite(left.start, left.end, `var ${moduleName}`);
} else {
const _match = _slicedToArray(match, 2),
name = _match[1];
const deconflicted = deconflict(scope, globals, name);
names.push({
name,
deconflicted
});
magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
const declaration = name === deconflicted ? `export { ${name} };` : `export { ${deconflicted} as ${name} };`;
if (name !== 'default') {
namedExportDeclarations.push({
str: declaration,
name
});
delete namedExports[name];
}
defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
}
}
});
if (!hasDefaultExport && (names.length || !isEntry)) {
wrapperEnd = `\n\nvar ${moduleName} = {\n${names.map(({
name,
deconflicted
}) => `\t${name}: ${deconflicted}`).join(',\n')}\n};`;
}
}
Object.keys(namedExports).filter(key => !blacklist[key]).forEach(addExport);
const defaultExport = /__esModule/.test(code) ? `export default ${HELPERS_NAME}.unwrapExports(${moduleName});` : `export default ${moduleName};`;
const named = namedExportDeclarations.filter(x => x.name !== 'default' || !hasDefaultExport).map(x => x.str);
const exportBlock = `\n\n${[defaultExport].concat(named).concat(hasDefaultExport ? defaultExportPropertyAssignments : []).join('\n')}`;
magicString.trim().prepend(importBlock + wrapperStart).trim().append(wrapperEnd);
if (hasDefaultExport || named.length > 0 || shouldWrap || !isEntry) {
magicString.append(exportBlock);
}
code = magicString.toString();
const map = sourceMap ? magicString.generateMap() : null;
return {
code,
map
};
}
function commonjs(options = {}) {
const extensions = options.extensions || ['.js'];
const filter = createFilter(options.include, options.exclude);
const ignoreGlobal = options.ignoreGlobal;
const customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach(id => {
let resolveId = id;
let resolvedId;
if (isCore(id)) {
// resolve will not find npm modules with the same name as
// core modules without a trailing slash. Since core modules
// must be external, we can assume any core modules defined
// here are npm modules by that name.
resolveId += '/';
}
try {
resolvedId = sync(resolveId, {
basedir: process.cwd()
});
} catch (err) {
resolvedId = resolve(id);
} // Note: customNamedExport's keys must be normalized file paths.
// resolve and nodeResolveSync both return normalized file paths
// so no additional normalization is necessary.
customNamedExports[resolvedId] = options.namedExports[id];
if (existsSync(resolvedId)) {
const realpath = realpathSync(resolvedId);
if (realpath !== resolvedId) {
customNamedExports[realpath] = options.namedExports[id];
}
}
});
}
const esModulesWithoutDefaultExport = new Set();
const esModulesWithDefaultExport = new Set(); // TODO maybe this should be configurable?
const allowDynamicRequire = !!options.ignore;
const ignoreRequire = typeof options.ignore === 'function' ? options.ignore : Array.isArray(options.ignore) ? id => options.ignore.includes(id) : () => false;
const resolveId = getResolveId(extensions);
const sourceMap = options.sourceMap !== false;
function transformAndCheckExports(code, id) {
const _checkEsModule = checkEsModule(this.parse, code, id),
isEsModule = _checkEsModule.isEsModule,
hasDefaultExport = _checkEsModule.hasDefaultExport,
ast = _checkEsModule.ast;
if (isEsModule) {
(hasDefaultExport ? esModulesWithDefaultExport : esModulesWithoutDefaultExport).add(id);
return null;
} // it is not an ES module but it does not have CJS-specific elements.
if (!hasCjsKeywords(code, ignoreGlobal)) {
esModulesWithoutDefaultExport.add(id);
return null;
}
const normalizedId = normalize(id);
const transformed = transformCommonjs(this.parse, code, id, this.getModuleInfo(id).isEntry, ignoreGlobal, ignoreRequire, customNamedExports[normalizedId], sourceMap, allowDynamicRequire, ast);
if (!transformed) {
esModulesWithoutDefaultExport.add(id);
return null;
}
return transformed;
}
return {
name: 'commonjs',
buildStart() {
const _this$meta$rollupVers = this.meta.rollupVersion.split('.').map(Number),
_this$meta$rollupVers2 = _slicedToArray(_this$meta$rollupVers, 2),
major = _this$meta$rollupVers2[0],
minor = _this$meta$rollupVers2[1];
const minVersion = peerDependencies.rollup.slice(2);
const _minVersion$split$map = minVersion.split('.').map(Number),
_minVersion$split$map2 = _slicedToArray(_minVersion$split$map, 2),
minMajor = _minVersion$split$map2[0],
minMinor = _minVersion$split$map2[1];
if (major < minMajor || major === minMajor && minor < minMinor) {
this.error(`Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`);
}
},
resolveId,
load(id) {
if (id === HELPERS_ID) return HELPERS; // generate proxy modules
if (id.endsWith(EXTERNAL_SUFFIX)) {
const actualId = getIdFromExternalProxyId(id);
const name = getName(actualId);
return `import ${name} from ${JSON.stringify(actualId)}; export default ${name};`;
}
if (id.endsWith(PROXY_SUFFIX)) {
const actualId = getIdFromProxyId(id);
const name = getName(actualId);
return getIsCjsPromise(actualId).then(isCjs => {
if (isCjs) return `import { __moduleExports } from ${JSON.stringify(actualId)}; export default __moduleExports;`;else if (esModulesWithoutDefaultExport.has(actualId)) return `import * as ${name} from ${JSON.stringify(actualId)}; export default ${name};`;else if (esModulesWithDefaultExport.has(actualId)) {
return `export {default} from ${JSON.stringify(actualId)};`;
}
return `import * as ${name} from ${JSON.stringify(actualId)}; import {getCjsExportFromNamespace} from "${HELPERS_ID}"; export default getCjsExportFromNamespace(${name})`;
});
}
return null;
},
transform(code, id) {
if (!filter(id) || extensions.indexOf(extname(id)) === -1) {
setIsCjsPromise(id, null);
return null;
}
let transformed;
try {
transformed = transformAndCheckExports.call(this, code, id);
} catch (err) {
transformed = null;
this.error(err, err.loc);
}
setIsCjsPromise(id, Boolean(transformed));
return transformed;
}
};
}
export default commonjs;
//# sourceMappingURL=index.es.js.map

File diff suppressed because one or more lines are too long

897
node_modules/@rollup/plugin-commonjs/dist/index.js generated vendored Normal file
View File

@ -0,0 +1,897 @@
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var fs = require('fs');
var path = require('path');
var resolve = require('resolve');
var pluginutils = require('@rollup/pluginutils');
var estreeWalker = require('estree-walker');
var MagicString = _interopDefault(require('magic-string'));
var isReference = _interopDefault(require('is-reference'));
function _slicedToArray(arr, i) {
return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _nonIterableRest();
}
function _arrayWithHoles(arr) {
if (Array.isArray(arr)) return arr;
}
function _iterableToArrayLimit(arr, i) {
if (!(Symbol.iterator in Object(arr) || Object.prototype.toString.call(arr) === "[object Arguments]")) {
return;
}
var _arr = [];
var _n = true;
var _d = false;
var _e = undefined;
try {
for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) {
_arr.push(_s.value);
if (i && _arr.length === i) break;
}
} catch (err) {
_d = true;
_e = err;
} finally {
try {
if (!_n && _i["return"] != null) _i["return"]();
} finally {
if (_d) throw _e;
}
}
return _arr;
}
function _nonIterableRest() {
throw new TypeError("Invalid attempt to destructure non-iterable instance");
}
var peerDependencies = {
rollup: "^1.20.0"
};
const PROXY_SUFFIX = '?commonjs-proxy';
const getProxyId = id => `\0${id}${PROXY_SUFFIX}`;
const getIdFromProxyId = proxyId => proxyId.slice(1, -PROXY_SUFFIX.length);
const EXTERNAL_SUFFIX = '?commonjs-external';
const getExternalProxyId = id => `\0${id}${EXTERNAL_SUFFIX}`;
const getIdFromExternalProxyId = proxyId => proxyId.slice(1, -EXTERNAL_SUFFIX.length);
const HELPERS_ID = '\0commonjsHelpers.js'; // `x['default']` is used instead of `x.default` for backward compatibility with ES3 browsers.
// Minifiers like uglify will usually transpile it back if compatibility with ES3 is not enabled.
const HELPERS = `
export var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
export function commonjsRequire () {
throw new Error('Dynamic requires are not currently supported by @rollup/plugin-commonjs');
}
export function unwrapExports (x) {
return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x;
}
export function createCommonjsModule(fn, module) {
return module = { exports: {} }, fn(module, module.exports), module.exports;
}
export function getCjsExportFromNamespace (n) {
return n && n['default'] || n;
}`;
/* eslint-disable no-undefined */
const isCjsPromises = new Map();
function getIsCjsPromise(id) {
let isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) return isCjsPromise.promise;
const promise = new Promise(resolve => {
isCjsPromise = {
resolve,
promise: undefined
};
isCjsPromises.set(id, isCjsPromise);
});
isCjsPromise.promise = promise;
return promise;
}
function setIsCjsPromise(id, resolution) {
const isCjsPromise = isCjsPromises.get(id);
if (isCjsPromise) {
if (isCjsPromise.resolve) {
isCjsPromise.resolve(resolution);
isCjsPromise.resolve = undefined;
}
} else {
isCjsPromises.set(id, {
promise: Promise.resolve(resolution),
resolve: undefined
});
}
}
/* eslint-disable no-param-reassign, no-undefined */
function getCandidatesForExtension(resolved, extension) {
return [resolved + extension, `${resolved}${path.sep}index${extension}`];
}
function getCandidates(resolved, extensions) {
return extensions.reduce((paths, extension) => paths.concat(getCandidatesForExtension(resolved, extension)), [resolved]);
}
function getResolveId(extensions) {
function resolveExtensions(importee, importer) {
// not our problem
if (importee[0] !== '.' || !importer) return undefined;
const resolved = path.resolve(path.dirname(importer), importee);
const candidates = getCandidates(resolved, extensions);
for (let i = 0; i < candidates.length; i += 1) {
try {
const stats = fs.statSync(candidates[i]);
if (stats.isFile()) return {
id: candidates[i]
};
} catch (err) {
/* noop */
}
}
return undefined;
}
function resolveId(importee, importer) {
const isProxyModule = importee.endsWith(PROXY_SUFFIX);
if (isProxyModule) {
importee = getIdFromProxyId(importee);
} else if (importee.startsWith('\0')) {
if (importee === HELPERS_ID) {
return importee;
}
return null;
}
if (importer && importer.endsWith(PROXY_SUFFIX)) {
importer = getIdFromProxyId(importer);
}
return this.resolve(importee, importer, {
skipSelf: true
}).then(resolved => {
if (!resolved) {
resolved = resolveExtensions(importee, importer);
}
if (isProxyModule) {
if (!resolved) {
return {
id: getExternalProxyId(importee),
external: false
};
}
resolved.id = (resolved.external ? getExternalProxyId : getProxyId)(resolved.id);
resolved.external = false;
return resolved;
}
return resolved;
});
}
return resolveId;
}
/* eslint-disable no-undefined */
const operators = {
'==': x => equals(x.left, x.right, false),
'!=': x => not(operators['=='](x)),
'===': x => equals(x.left, x.right, true),
'!==': x => not(operators['==='](x)),
'!': x => isFalsy(x.argument),
'&&': x => isTruthy(x.left) && isTruthy(x.right),
'||': x => isTruthy(x.left) || isTruthy(x.right)
};
function flatten(node) {
const parts = [];
while (node.type === 'MemberExpression') {
if (node.computed) return null;
parts.unshift(node.property.name); // eslint-disable-next-line no-param-reassign
node = node.object;
}
if (node.type !== 'Identifier') return null;
const _node = node,
name = _node.name;
parts.unshift(name);
return {
name,
keypath: parts.join('.')
};
}
function isTruthy(node) {
if (node.type === 'Literal') return !!node.value;
if (node.type === 'ParenthesizedExpression') return isTruthy(node.expression);
if (node.operator in operators) return operators[node.operator](node);
return undefined;
}
function isFalsy(node) {
return not(isTruthy(node));
}
function not(value) {
return value === undefined ? value : !value;
}
function equals(a, b, strict) {
if (a.type !== b.type) return undefined; // eslint-disable-next-line eqeqeq
if (a.type === 'Literal') return strict ? a.value === b.value : a.value == b.value;
return undefined;
}
/* eslint-disable import/prefer-default-export */
function getName(id) {
const name = pluginutils.makeLegalIdentifier(path.basename(id, path.extname(id)));
if (name !== 'index') {
return name;
}
const segments = path.dirname(id).split(path.sep);
return pluginutils.makeLegalIdentifier(segments[segments.length - 1]);
}
const reserved = 'process location abstract arguments boolean break byte case catch char class const continue debugger default delete do double else enum eval export extends false final finally float for from function goto if implements import in instanceof int interface let long native new null package private protected public return short static super switch synchronized this throw throws transient true try typeof var void volatile while with yield'.split(' ');
const blacklist = {
__esModule: true
};
reserved.forEach(word => blacklist[word] = true);
const exportsPattern = /^(?:module\.)?exports(?:\.([a-zA-Z_$][a-zA-Z_$0-9]*))?$/;
const firstpassGlobal = /\b(?:require|module|exports|global)\b/;
const firstpassNoGlobal = /\b(?:require|module|exports)\b/;
const importExportDeclaration = /^(?:Import|Export(?:Named|Default))Declaration/;
const functionType = /^(?:FunctionDeclaration|FunctionExpression|ArrowFunctionExpression)$/;
function deconflict(scope, globals, identifier) {
let i = 1;
let deconflicted = identifier;
while (scope.contains(deconflicted) || globals.has(deconflicted) || deconflicted in blacklist) {
deconflicted = `${identifier}_${i}`;
i += 1;
}
scope.declarations[deconflicted] = true;
return deconflicted;
}
function tryParse(parse, code, id) {
try {
return parse(code, {
allowReturnOutsideFunction: true
});
} catch (err) {
err.message += ` in ${id}`;
throw err;
}
}
function hasCjsKeywords(code, ignoreGlobal) {
const firstpass = ignoreGlobal ? firstpassNoGlobal : firstpassGlobal;
return firstpass.test(code);
}
function checkEsModule(parse, code, id) {
const ast = tryParse(parse, code, id);
let isEsModule = false;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = ast.body[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const node = _step.value;
if (node.type === 'ExportDefaultDeclaration') return {
isEsModule: true,
hasDefaultExport: true,
ast
};
if (node.type === 'ExportNamedDeclaration') {
isEsModule = true;
var _iteratorNormalCompletion2 = true;
var _didIteratorError2 = false;
var _iteratorError2 = undefined;
try {
for (var _iterator2 = node.specifiers[Symbol.iterator](), _step2; !(_iteratorNormalCompletion2 = (_step2 = _iterator2.next()).done); _iteratorNormalCompletion2 = true) {
const specifier = _step2.value;
if (specifier.exported.name === 'default') {
return {
isEsModule: true,
hasDefaultExport: true,
ast
};
}
}
} catch (err) {
_didIteratorError2 = true;
_iteratorError2 = err;
} finally {
try {
if (!_iteratorNormalCompletion2 && _iterator2.return != null) {
_iterator2.return();
}
} finally {
if (_didIteratorError2) {
throw _iteratorError2;
}
}
}
} else if (importExportDeclaration.test(node.type)) isEsModule = true;
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
return {
isEsModule,
hasDefaultExport: false,
ast
};
}
function transformCommonjs(parse, code, id, isEntry, ignoreGlobal, ignoreRequire, customNamedExports, sourceMap, allowDynamicRequire, astCache) {
const ast = astCache || tryParse(parse, code, id);
const magicString = new MagicString(code);
const required = {}; // Because objects have no guaranteed ordering, yet we need it,
// we need to keep track of the order in a array
const sources = [];
let uid = 0;
let scope = pluginutils.attachScopes(ast, 'scope');
const uses = {
module: false,
exports: false,
global: false,
require: false
};
let lexicalDepth = 0;
let programDepth = 0;
const globals = new Set(); // TODO technically wrong since globals isn't populated yet, but ¯\_(ツ)_/¯
const HELPERS_NAME = deconflict(scope, globals, 'commonjsHelpers');
const namedExports = {}; // TODO handle transpiled modules
let shouldWrap = /__esModule/.test(code);
function isRequireStatement(node) {
if (!node) return false;
if (node.type !== 'CallExpression') return false;
if (node.callee.name !== 'require' || scope.contains('require')) return false; // Weird case of require() without arguments
if (node.arguments.length === 0) return false;
return true;
}
function hasDynamicArguments(node) {
return node.arguments.length > 1 || node.arguments[0].type !== 'Literal' && (node.arguments[0].type !== 'TemplateLiteral' || node.arguments[0].expressions.length > 0);
}
function isStaticRequireStatement(node) {
if (!isRequireStatement(node)) return false;
if (hasDynamicArguments(node)) return false;
if (ignoreRequire(node.arguments[0].value)) return false;
return true;
}
function getRequireStringArg(node) {
return node.arguments[0].type === 'Literal' ? node.arguments[0].value : node.arguments[0].quasis[0].value.cooked;
}
function getRequired(node, name) {
const sourceId = getRequireStringArg(node);
const existing = required[sourceId]; // eslint-disable-next-line no-undefined
if (existing === undefined) {
if (!name) {
do {
name = `require$$${uid}`;
uid += 1;
} while (scope.contains(name));
}
sources.push(sourceId);
required[sourceId] = {
source: sourceId,
name,
importsDefault: false
};
}
return required[sourceId];
} // do a first pass, see which names are assigned to. This is necessary to prevent
// illegally replacing `var foo = require('foo')` with `import foo from 'foo'`,
// where `foo` is later reassigned. (This happens in the wild. CommonJS, sigh)
const assignedTo = new Set();
estreeWalker.walk(ast, {
enter(node) {
if (node.type !== 'AssignmentExpression') return;
if (node.left.type === 'MemberExpression') return;
pluginutils.extractAssignedNames(node.left).forEach(name => {
assignedTo.add(name);
});
}
});
estreeWalker.walk(ast, {
enter(node, parent) {
if (sourceMap) {
magicString.addSourcemapLocation(node.start);
magicString.addSourcemapLocation(node.end);
} // skip dead branches
if (parent && (parent.type === 'IfStatement' || parent.type === 'ConditionalExpression')) {
if (node === parent.consequent && isFalsy(parent.test)) {
this.skip();
return;
}
if (node === parent.alternate && isTruthy(parent.test)) {
this.skip();
return;
}
}
if (node._skip) {
this.skip();
return;
}
programDepth += 1;
if (node.scope) {
scope = node.scope;
}
if (functionType.test(node.type)) lexicalDepth += 1; // if toplevel return, we need to wrap it
if (node.type === 'ReturnStatement' && lexicalDepth === 0) {
shouldWrap = true;
} // rewrite `this` as `commonjsHelpers.commonjsGlobal`
if (node.type === 'ThisExpression' && lexicalDepth === 0) {
uses.global = true;
if (!ignoreGlobal) magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
return;
} // rewrite `typeof module`, `typeof module.exports` and `typeof exports` (https://github.com/rollup/rollup-plugin-commonjs/issues/151)
if (node.type === 'UnaryExpression' && node.operator === 'typeof') {
const flattened = flatten(node.argument);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
if (flattened.keypath === 'module.exports' || flattened.keypath === 'module' || flattened.keypath === 'exports') {
magicString.overwrite(node.start, node.end, `'object'`, {
storeName: false
});
}
} // rewrite `require` (if not already handled) `global` and `define`, and handle free references to
// `module` and `exports` as these mean we need to wrap the module in commonjsHelpers.createCommonjsModule
if (node.type === 'Identifier') {
if (isReference(node, parent) && !scope.contains(node.name)) {
if (node.name in uses) {
if (node.name === 'require') {
if (allowDynamicRequire) return;
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsRequire`, {
storeName: true
});
}
uses[node.name] = true;
if (node.name === 'global' && !ignoreGlobal) {
magicString.overwrite(node.start, node.end, `${HELPERS_NAME}.commonjsGlobal`, {
storeName: true
});
} // if module or exports are used outside the context of an assignment
// expression, we need to wrap the module
if (node.name === 'module' || node.name === 'exports') {
shouldWrap = true;
}
}
if (node.name === 'define') {
magicString.overwrite(node.start, node.end, 'undefined', {
storeName: true
});
}
globals.add(node.name);
}
return;
} // Is this an assignment to exports or module.exports?
if (node.type === 'AssignmentExpression') {
if (node.left.type !== 'MemberExpression') return;
const flattened = flatten(node.left);
if (!flattened) return;
if (scope.contains(flattened.name)) return;
const match = exportsPattern.exec(flattened.keypath);
if (!match || flattened.keypath === 'exports') return;
uses[flattened.name] = true; // we're dealing with `module.exports = ...` or `[module.]exports.foo = ...`
// if this isn't top-level, we'll need to wrap the module
if (programDepth > 3) shouldWrap = true;
node.left._skip = true;
if (flattened.keypath === 'module.exports' && node.right.type === 'ObjectExpression') {
node.right.properties.forEach(prop => {
if (prop.computed || !('key' in prop) || prop.key.type !== 'Identifier') return;
const name = prop.key.name;
if (name === pluginutils.makeLegalIdentifier(name)) namedExports[name] = true;
});
return;
}
if (match[1]) namedExports[match[1]] = true;
return;
} // if this is `var x = require('x')`, we can do `import x from 'x'`
if (node.type === 'VariableDeclarator' && node.id.type === 'Identifier' && isStaticRequireStatement(node.init)) {
// for now, only do this for top-level requires. maybe fix this in future
if (scope.parent) return; // edge case — CJS allows you to assign to imports. ES doesn't
if (assignedTo.has(node.id.name)) return;
const required = getRequired(node.init, node.id.name);
required.importsDefault = true;
if (required.name === node.id.name) {
node._shouldRemove = true;
}
}
if (!isStaticRequireStatement(node)) return;
const required = getRequired(node);
if (parent.type === 'ExpressionStatement') {
// is a bare import, e.g. `require('foo');`
magicString.remove(parent.start, parent.end);
} else {
required.importsDefault = true;
magicString.overwrite(node.start, node.end, required.name);
}
node.callee._skip = true;
},
leave(node) {
programDepth -= 1;
if (node.scope) scope = scope.parent;
if (functionType.test(node.type)) lexicalDepth -= 1;
if (node.type === 'VariableDeclaration') {
let keepDeclaration = false;
let c = node.declarations[0].start;
for (let i = 0; i < node.declarations.length; i += 1) {
const declarator = node.declarations[i];
if (declarator._shouldRemove) {
magicString.remove(c, declarator.end);
} else {
if (!keepDeclaration) {
magicString.remove(c, declarator.start);
keepDeclaration = true;
}
c = declarator.end;
}
}
if (!keepDeclaration) {
magicString.remove(node.start, node.end);
}
}
}
});
if (!sources.length && !uses.module && !uses.exports && !uses.require && (ignoreGlobal || !uses.global)) {
if (Object.keys(namedExports).length) {
throw new Error(`Custom named exports were specified for ${id} but it does not appear to be a CommonJS module`);
} // not a CommonJS module
return null;
}
const includeHelpers = shouldWrap || uses.global || uses.require;
const importBlock = `${(includeHelpers ? [`import * as ${HELPERS_NAME} from '${HELPERS_ID}';`] : []).concat(sources.map(source => // import the actual module before the proxy, so that we know
// what kind of proxy to build
`import '${source}';`), sources.map(source => {
const _required$source = required[source],
name = _required$source.name,
importsDefault = _required$source.importsDefault;
return `import ${importsDefault ? `${name} from ` : ``}'${getProxyId(source)}';`;
})).join('\n')}\n\n`;
const namedExportDeclarations = [];
let wrapperStart = '';
let wrapperEnd = '';
const moduleName = deconflict(scope, globals, getName(id));
if (!isEntry) {
const exportModuleExports = {
str: `export { ${moduleName} as __moduleExports };`,
name: '__moduleExports'
};
namedExportDeclarations.push(exportModuleExports);
}
const name = getName(id);
function addExport(x) {
const deconflicted = deconflict(scope, globals, name);
const declaration = deconflicted === name ? `export var ${x} = ${moduleName}.${x};` : `var ${deconflicted} = ${moduleName}.${x};\nexport { ${deconflicted} as ${x} };`;
namedExportDeclarations.push({
str: declaration,
name: x
});
}
if (customNamedExports) customNamedExports.forEach(addExport);
const defaultExportPropertyAssignments = [];
let hasDefaultExport = false;
if (shouldWrap) {
const args = `module${uses.exports ? ', exports' : ''}`;
wrapperStart = `var ${moduleName} = ${HELPERS_NAME}.createCommonjsModule(function (${args}) {\n`;
wrapperEnd = `\n});`;
} else {
const names = [];
ast.body.forEach(node => {
if (node.type === 'ExpressionStatement' && node.expression.type === 'AssignmentExpression') {
const left = node.expression.left;
const flattened = flatten(left);
if (!flattened) return;
const match = exportsPattern.exec(flattened.keypath);
if (!match) return;
if (flattened.keypath === 'module.exports') {
hasDefaultExport = true;
magicString.overwrite(left.start, left.end, `var ${moduleName}`);
} else {
const _match = _slicedToArray(match, 2),
name = _match[1];
const deconflicted = deconflict(scope, globals, name);
names.push({
name,
deconflicted
});
magicString.overwrite(node.start, left.end, `var ${deconflicted}`);
const declaration = name === deconflicted ? `export { ${name} };` : `export { ${deconflicted} as ${name} };`;
if (name !== 'default') {
namedExportDeclarations.push({
str: declaration,
name
});
delete namedExports[name];
}
defaultExportPropertyAssignments.push(`${moduleName}.${name} = ${deconflicted};`);
}
}
});
if (!hasDefaultExport && (names.length || !isEntry)) {
wrapperEnd = `\n\nvar ${moduleName} = {\n${names.map(({
name,
deconflicted
}) => `\t${name}: ${deconflicted}`).join(',\n')}\n};`;
}
}
Object.keys(namedExports).filter(key => !blacklist[key]).forEach(addExport);
const defaultExport = /__esModule/.test(code) ? `export default ${HELPERS_NAME}.unwrapExports(${moduleName});` : `export default ${moduleName};`;
const named = namedExportDeclarations.filter(x => x.name !== 'default' || !hasDefaultExport).map(x => x.str);
const exportBlock = `\n\n${[defaultExport].concat(named).concat(hasDefaultExport ? defaultExportPropertyAssignments : []).join('\n')}`;
magicString.trim().prepend(importBlock + wrapperStart).trim().append(wrapperEnd);
if (hasDefaultExport || named.length > 0 || shouldWrap || !isEntry) {
magicString.append(exportBlock);
}
code = magicString.toString();
const map = sourceMap ? magicString.generateMap() : null;
return {
code,
map
};
}
function commonjs(options = {}) {
const extensions = options.extensions || ['.js'];
const filter = pluginutils.createFilter(options.include, options.exclude);
const ignoreGlobal = options.ignoreGlobal;
const customNamedExports = {};
if (options.namedExports) {
Object.keys(options.namedExports).forEach(id => {
let resolveId = id;
let resolvedId;
if (resolve.isCore(id)) {
// resolve will not find npm modules with the same name as
// core modules without a trailing slash. Since core modules
// must be external, we can assume any core modules defined
// here are npm modules by that name.
resolveId += '/';
}
try {
resolvedId = resolve.sync(resolveId, {
basedir: process.cwd()
});
} catch (err) {
resolvedId = path.resolve(id);
} // Note: customNamedExport's keys must be normalized file paths.
// resolve and nodeResolveSync both return normalized file paths
// so no additional normalization is necessary.
customNamedExports[resolvedId] = options.namedExports[id];
if (fs.existsSync(resolvedId)) {
const realpath = fs.realpathSync(resolvedId);
if (realpath !== resolvedId) {
customNamedExports[realpath] = options.namedExports[id];
}
}
});
}
const esModulesWithoutDefaultExport = new Set();
const esModulesWithDefaultExport = new Set(); // TODO maybe this should be configurable?
const allowDynamicRequire = !!options.ignore;
const ignoreRequire = typeof options.ignore === 'function' ? options.ignore : Array.isArray(options.ignore) ? id => options.ignore.includes(id) : () => false;
const resolveId = getResolveId(extensions);
const sourceMap = options.sourceMap !== false;
function transformAndCheckExports(code, id) {
const _checkEsModule = checkEsModule(this.parse, code, id),
isEsModule = _checkEsModule.isEsModule,
hasDefaultExport = _checkEsModule.hasDefaultExport,
ast = _checkEsModule.ast;
if (isEsModule) {
(hasDefaultExport ? esModulesWithDefaultExport : esModulesWithoutDefaultExport).add(id);
return null;
} // it is not an ES module but it does not have CJS-specific elements.
if (!hasCjsKeywords(code, ignoreGlobal)) {
esModulesWithoutDefaultExport.add(id);
return null;
}
const normalizedId = path.normalize(id);
const transformed = transformCommonjs(this.parse, code, id, this.getModuleInfo(id).isEntry, ignoreGlobal, ignoreRequire, customNamedExports[normalizedId], sourceMap, allowDynamicRequire, ast);
if (!transformed) {
esModulesWithoutDefaultExport.add(id);
return null;
}
return transformed;
}
return {
name: 'commonjs',
buildStart() {
const _this$meta$rollupVers = this.meta.rollupVersion.split('.').map(Number),
_this$meta$rollupVers2 = _slicedToArray(_this$meta$rollupVers, 2),
major = _this$meta$rollupVers2[0],
minor = _this$meta$rollupVers2[1];
const minVersion = peerDependencies.rollup.slice(2);
const _minVersion$split$map = minVersion.split('.').map(Number),
_minVersion$split$map2 = _slicedToArray(_minVersion$split$map, 2),
minMajor = _minVersion$split$map2[0],
minMinor = _minVersion$split$map2[1];
if (major < minMajor || major === minMajor && minor < minMinor) {
this.error(`Insufficient Rollup version: "@rollup/plugin-commonjs" requires at least rollup@${minVersion} but found rollup@${this.meta.rollupVersion}.`);
}
},
resolveId,
load(id) {
if (id === HELPERS_ID) return HELPERS; // generate proxy modules
if (id.endsWith(EXTERNAL_SUFFIX)) {
const actualId = getIdFromExternalProxyId(id);
const name = getName(actualId);
return `import ${name} from ${JSON.stringify(actualId)}; export default ${name};`;
}
if (id.endsWith(PROXY_SUFFIX)) {
const actualId = getIdFromProxyId(id);
const name = getName(actualId);
return getIsCjsPromise(actualId).then(isCjs => {
if (isCjs) return `import { __moduleExports } from ${JSON.stringify(actualId)}; export default __moduleExports;`;else if (esModulesWithoutDefaultExport.has(actualId)) return `import * as ${name} from ${JSON.stringify(actualId)}; export default ${name};`;else if (esModulesWithDefaultExport.has(actualId)) {
return `export {default} from ${JSON.stringify(actualId)};`;
}
return `import * as ${name} from ${JSON.stringify(actualId)}; import {getCjsExportFromNamespace} from "${HELPERS_ID}"; export default getCjsExportFromNamespace(${name})`;
});
}
return null;
},
transform(code, id) {
if (!filter(id) || extensions.indexOf(path.extname(id)) === -1) {
setIsCjsPromise(id, null);
return null;
}
let transformed;
try {
transformed = transformAndCheckExports.call(this, code, id);
} catch (err) {
transformed = null;
this.error(err, err.loc);
}
setIsCjsPromise(id, Boolean(transformed));
return transformed;
}
};
}
module.exports = commonjs;
//# sourceMappingURL=index.js.map

File diff suppressed because one or more lines are too long

120
node_modules/@rollup/plugin-commonjs/package.json generated vendored Normal file
View File

@ -0,0 +1,120 @@
{
"_from": "@rollup/plugin-commonjs",
"_id": "@rollup/plugin-commonjs@11.0.2",
"_inBundle": false,
"_integrity": "sha512-MPYGZr0qdbV5zZj8/2AuomVpnRVXRU5XKXb3HVniwRoRCreGlf5kOE081isNWeiLIi6IYkwTX9zE0/c7V8g81g==",
"_location": "/@rollup/plugin-commonjs",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "@rollup/plugin-commonjs",
"name": "@rollup/plugin-commonjs",
"escapedName": "@rollup%2fplugin-commonjs",
"scope": "@rollup",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/@rollup/plugin-commonjs/-/plugin-commonjs-11.0.2.tgz",
"_shasum": "837cc6950752327cb90177b608f0928a4e60b582",
"_spec": "@rollup/plugin-commonjs",
"_where": "/home/juan/bigint-crypto-utils",
"author": {
"name": "Rich Harris",
"email": "richard.a.harris@gmail.com"
},
"ava": {
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"bundleDependencies": false,
"dependencies": {
"@rollup/pluginutils": "^3.0.0",
"estree-walker": "^1.0.1",
"is-reference": "^1.1.2",
"magic-string": "^0.25.2",
"resolve": "^1.11.0"
},
"deprecated": false,
"description": "Convert CommonJS modules to ES2015",
"devDependencies": {
"@babel/core": "^7.7.7",
"@babel/preset-env": "^7.7.7",
"@babel/register": "^7.7.7",
"@rollup/plugin-json": "^4.0.1",
"@rollup/plugin-node-resolve": "^7.0.0",
"acorn": "^7.1.0",
"locate-character": "^2.0.5",
"prettier": "^1.19.1",
"require-relative": "^0.8.7",
"rollup": "^1.27.14",
"rollup-plugin-babel": "^4.3.3",
"shx": "^0.3.2",
"source-map": "^0.6.1",
"source-map-support": "^0.5.16",
"typescript": "^3.7.4"
},
"engines": {
"node": ">= 8.0.0"
},
"files": [
"dist",
"types",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/rollup/plugins/tree/master/packages/commonjs/#readme",
"keywords": [
"rollup",
"plugin",
"npm",
"modules",
"commonjs",
"require"
],
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.es.js",
"name": "@rollup/plugin-commonjs",
"peerDependencies": {
"rollup": "^1.20.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/plugins.git"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm run test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm run build && pnpm run lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm run test -- --verbose && pnpm run test:ts",
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
"lint:docs": "prettier --single-quote --write README.md",
"lint:js": "eslint --fix --cache src test",
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
"prebuild": "del-cli dist",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run lint && pnpm run test && pnpm run test:ts",
"pretest": "pnpm run build",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
},
"types": "types/index.d.ts",
"version": "11.0.2"
}

50
node_modules/@rollup/plugin-commonjs/types/index.d.ts generated vendored Normal file
View File

@ -0,0 +1,50 @@
import { Plugin } from 'rollup';
interface RollupCommonJSOptions {
/**
* non-CommonJS modules will be ignored, but you can also
* specifically include/exclude files
* @default undefined
*/
include?: string | RegExp | ReadonlyArray<string | RegExp>,
/**
* non-CommonJS modules will be ignored, but you can also
* specifically include/exclude files
* @default undefined
*/
exclude?: string | RegExp | ReadonlyArray<string | RegExp>,
/**
* search for files other than .js files (must already
* be transpiled by a previous plugin!)
* @default [ '.js' ]
*/
extensions?: ReadonlyArray<string | RegExp>,
/**
* if true then uses of `global` won't be dealt with by this plugin
* @default false
*/
ignoreGlobal?: boolean,
/**
* if false then skip sourceMap generation for CommonJS modules
* @default true
*/
sourceMap?: boolean,
/**
* explicitly specify unresolvable named exports
* ([see below for more details](https://github.com/rollup/plugins/tree/master/packages/commonjs#named-exports))
* @default undefined
*/
namedExports?: { [package: string]: ReadonlyArray<string> },
/**
* sometimes you have to leave require statements
* unconverted. Pass an array containing the IDs
* or a `id => boolean` function. Only use this
* option if you know what you're doing!
*/
ignore?: ReadonlyArray<string | ((id: string) => boolean)>,
}
/**
* Convert CommonJS modules to ES6, so they can be included in a Rollup bundle
*/
export default function commonjs(options?: RollupCommonJSOptions): Plugin;

7
node_modules/@rollup/plugin-multi-entry/CHANGELOG.md generated vendored Normal file
View File

@ -0,0 +1,7 @@
# @rollup/plugin-multi-entry Change Log
## 3.0.0
_2019-12-15_
- First publish of scoped package. For details on prior versions, please see https://github.com/rollup/rollup-plugin-multi-entry/releases

21
node_modules/@rollup/plugin-multi-entry/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
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.

125
node_modules/@rollup/plugin-multi-entry/README.md generated vendored Executable file
View File

@ -0,0 +1,125 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-multi-entry
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-multi-entry
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-multi-entry
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-multi-entry
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-multi-entry
🍣 A Rollup plugin which allows use of multiple entry points for a bundle.
As an added bonus, the _named exports_ from all entry points will be combined. This is particularly useful for tests, but can also be used to package a library.
_Note: `default` exports cannot be combined and exported by this plugin. Only named exports will be exported._
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-multi-entry --save-dev
```
## Usage
Suppose that we have three separate source files, each with their own export(s):
```js
// batman.js
export const belt = 'utility';
```
```js
// robin.js
export const tights = 'tight';
```
```js
// joker.js
export const color = 'purple';
```
Then, create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import multi from '@rollup/plugin-multi-entry';
export default {
input: ['batman.js', 'robin.js', 'joker.js'],
output: {
dir: 'output'
},
plugins: [multi()]
};
```
Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
Using all three files above as entry points will yield a bundle with exports for `belt`, `tights`, and `color`.
## Options
### `exports`
Type: `Boolean`<br>
Default: `true`
If `true`, instructs the plugin to export named exports to the bundle from all entries. If `false`, the plugin will not export any entry exports to the bundle. This can be useful when wanting to combine code from multiple entry files, but not necessarily to export each entry file's exports.
## Supported Input Types
This plugin extends Rollup's `input` option to support multiple new value types, in addition to a `String` specifying a path to a file.
### Glob
When using `plugin-multi-entry`, input values passed as a normal `String` are [glob aware](<https://en.wikipedia.org/wiki/Glob_(programming)>). Meaning you can utilize glob wildcards and other glob patterns to specify files as being input files.
```js
export default {
input: 'batcave/friends/**/*.js',
plugins: [multi()]
// ...
};
```
### Array
An `Array` of `String` can be passed as the input. Values are glob-aware and can specify paths or globbed paths.
```js
export default {
input: ['party/supplies.js', 'batcave/friends/**/*.js'],
plugins: [multi()]
// ...
};
```
### `include` and `exclude`
For fine-grain control, an `Object` may be passed containing `include` and `exclude` properties. These properties specify and `Array` of `String` representing paths (which are also glob-aware) which should be included as entry files, as well as files that should be excluded from any entries that may have been found with `include`, respectively.
```js
export default {
input: {
// invite everyone!
include: ['food.js', 'drinks.js', 'batcave/friends/**/*.js'],
// except for the joker
exclude: ['**/joker.js']
},
plugins: [multi()]
// ...
};
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View File

@ -0,0 +1,61 @@
import { promise } from 'matched';
/* eslint-disable consistent-return, no-param-reassign */
const entry = '\0rollup:plugin-multi-entry:entry-point';
function multiEntry(conf) {
let include = [];
let exclude = [];
let exporter = path => `export * from ${JSON.stringify(path)};`;
function configure(config) {
if (typeof config === 'string') {
include = [config];
} else if (Array.isArray(config)) {
include = config;
} else {
include = config.include || [];
exclude = config.exclude || [];
if (config.exports === false) {
exporter = path => `import ${JSON.stringify(path)};`;
}
}
}
if (conf) {
configure(conf);
}
return {
options(options) {
if (options.input && options.input !== entry) {
configure(options.input);
}
options.input = entry;
},
resolveId(id) {
if (id === entry) {
return entry;
}
},
load(id) {
if (id === entry) {
if (!include.length) {
return Promise.resolve('');
}
const patterns = include.concat(exclude.map(pattern => `!${pattern}`));
return promise(patterns, {
realpath: true
}).then(paths => paths.map(exporter).join('\n'));
}
}
};
}
export default multiEntry;

63
node_modules/@rollup/plugin-multi-entry/dist/index.js generated vendored Normal file
View File

@ -0,0 +1,63 @@
'use strict';
var matched = require('matched');
/* eslint-disable consistent-return, no-param-reassign */
const entry = '\0rollup:plugin-multi-entry:entry-point';
function multiEntry(conf) {
let include = [];
let exclude = [];
let exporter = path => `export * from ${JSON.stringify(path)};`;
function configure(config) {
if (typeof config === 'string') {
include = [config];
} else if (Array.isArray(config)) {
include = config;
} else {
include = config.include || [];
exclude = config.exclude || [];
if (config.exports === false) {
exporter = path => `import ${JSON.stringify(path)};`;
}
}
}
if (conf) {
configure(conf);
}
return {
options(options) {
if (options.input && options.input !== entry) {
configure(options.input);
}
options.input = entry;
},
resolveId(id) {
if (id === entry) {
return entry;
}
},
load(id) {
if (id === entry) {
if (!include.length) {
return Promise.resolve('');
}
const patterns = include.concat(exclude.map(pattern => `!${pattern}`));
return matched.promise(patterns, {
realpath: true
}).then(paths => paths.map(exporter).join('\n'));
}
}
};
}
module.exports = multiEntry;

98
node_modules/@rollup/plugin-multi-entry/package.json generated vendored Normal file
View File

@ -0,0 +1,98 @@
{
"_from": "@rollup/plugin-multi-entry",
"_id": "@rollup/plugin-multi-entry@3.0.0",
"_inBundle": false,
"_integrity": "sha512-nFN+1hUHQn7Y6ivdJa/6sYo8LOTmtnQl7g4rQ3WgnJYkL0AByzpb3fXt70ANgJnoLmhcXHBQiQykg835EY7EMg==",
"_location": "/@rollup/plugin-multi-entry",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "@rollup/plugin-multi-entry",
"name": "@rollup/plugin-multi-entry",
"escapedName": "@rollup%2fplugin-multi-entry",
"scope": "@rollup",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/@rollup/plugin-multi-entry/-/plugin-multi-entry-3.0.0.tgz",
"_shasum": "3ad496146f4c792cc07d647cdcb407f74831c293",
"_spec": "@rollup/plugin-multi-entry",
"_where": "/home/juan/bigint-crypto-utils",
"author": {
"name": "rollup"
},
"ava": {
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"bundleDependencies": false,
"dependencies": {
"matched": "^1.0.2"
},
"deprecated": false,
"description": "Use multiple entry points for a bundle",
"devDependencies": {
"@babel/core": "^7.2.0",
"@babel/preset-env": "^7.2.0",
"rollup": "^1.20.1",
"rollup-plugin-babel": "^4.0.3"
},
"files": [
"dist",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/rollup/plugins/packages/multi-entry/#readme",
"keywords": [
"rollup",
"plugin",
"multi",
"multiple",
"entry",
"entries"
],
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.es.js",
"name": "@rollup/plugin-multi-entry",
"peerDependencies": {
"rollup": "^1.20.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/plugins.git"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm run test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm run build && pnpm run lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm run test -- --verbose",
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
"lint:docs": "prettier --single-quote --write README.md",
"lint:js": "eslint --fix --cache src test",
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
"prebuild": "del-cli dist",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run lint",
"pretest": "pnpm run build",
"test": "ava"
},
"version": "3.0.0"
}

254
node_modules/@rollup/plugin-node-resolve/CHANGELOG.md generated vendored Executable file
View File

@ -0,0 +1,254 @@
# @rollup/plugin-node-resolve ChangeLog
## v7.1.1
_2020-02-03_
### Bugfixes
- fix: main fields regression (#196)
## v7.1.0
_2020-02-01_
### Updates
- refactor: clean codebase and fix external warnings (#155)
## v7.0.0
_2020-01-07_
### Breaking Changes
- feat: dedupe by package name (#99)
## v6.1.0
_2020-01-04_
### Bugfixes
- fix: allow deduplicating custom module dirs (#101)
### Features
- feat: add rootDir option (#98)
### Updates
- docs: improve doc related to mainFields (#138)
## 6.0.0
_2019-11-25_
- **Breaking:** Minimum compatible Rollup version is 1.20.0
- **Breaking:** Minimum supported Node version is 8.0.0
- Published as @rollup/plugin-node-resolve
## 5.2.1 (unreleased)
- add missing MIT license file ([#233](https://github.com/rollup/rollup-plugin-node-resolve/pull/233) by @kenjiO)
- Fix incorrect example of config ([#239](https://github.com/rollup/rollup-plugin-node-resolve/pull/240) by @myshov)
- Fix typo in readme ([#240](https://github.com/rollup/rollup-plugin-node-resolve/pull/240) by @LinusU)
## 5.2.0 (2019-06-29)
- dedupe accepts a function ([#225](https://github.com/rollup/rollup-plugin-node-resolve/pull/225) by @manucorporat)
## 5.1.1 (2019-06-29)
- Move Rollup version check to buildStart hook to avoid issues ([#232](https://github.com/rollup/rollup-plugin-node-resolve/pull/232) by @lukastaegert)
## 5.1.0 (2019-06-22)
- Fix path fragment inputs ([#229](https://github.com/rollup/rollup-plugin-node-resolve/pull/229) by @bterlson)
## 5.0.4 (2019-06-22)
- Treat sideEffects array as inclusion list ([#227](https://github.com/rollup/rollup-plugin-node-resolve/pull/227) by @mikeharder)
## 5.0.3 (2019-06-16)
- Make empty.js a virtual module ([#224](https://github.com/rollup/rollup-plugin-node-resolve/pull/224) by @manucorporat)
## 5.0.2 (2019-06-13)
- Support resolve 1.11.1, add built-in test ([#223](https://github.com/rollup/rollup-plugin-node-resolve/pull/223) by @bterlson)
## 5.0.1 (2019-05-31)
- Update to resolve@1.11.0 for better performance ([#220](https://github.com/rollup/rollup-plugin-node-resolve/pull/220) by @keithamus)
## 5.0.0 (2019-05-15)
- Replace bublé with babel, update dependencies ([#216](https://github.com/rollup/rollup-plugin-node-resolve/pull/216) by @mecurc)
- Handle module side-effects ([#219](https://github.com/rollup/rollup-plugin-node-resolve/pull/219) by @lukastaegert)
### Breaking Changes
- Requires at least rollup@1.11.0 to work (v1.12.0 for module side-effects to be respected)
- If used with rollup-plugin-commonjs, it should be at least v10.0.0
## 4.2.4 (2019-05-11)
- Add note on builtins to Readme ([#215](https://github.com/rollup/rollup-plugin-node-resolve/pull/215) by @keithamus)
- Add issue templates ([#217](https://github.com/rollup/rollup-plugin-node-resolve/pull/217) by @mecurc)
- Improve performance by caching `isDir` ([#218](https://github.com/rollup/rollup-plugin-node-resolve/pull/218) by @keithamus)
## 4.2.3 (2019-04-11)
- Fix ordering of jsnext:main when using the jsnext option ([#209](https://github.com/rollup/rollup-plugin-node-resolve/pull/209) by @lukastaegert)
## 4.2.2 (2019-04-10)
- Fix TypeScript typings (rename and export Options interface) ([#206](https://github.com/rollup/rollup-plugin-node-resolve/pull/206) by @Kocal)
- Fix mainfields typing ([#207](https://github.com/rollup/rollup-plugin-node-resolve/pull/207) by @nicolashenry)
## 4.2.1 (2019-04-06)
- Respect setting the deprecated fields "module", "main", and "jsnext" ([#204](https://github.com/rollup/rollup-plugin-node-resolve/pull/204) by @nick-woodward)
## 4.2.0 (2019-04-06)
- Add new mainfields option ([#182](https://github.com/rollup/rollup-plugin-node-resolve/pull/182) by @keithamus)
- Added dedupe option to prevent bundling the same package multiple times ([#201](https://github.com/rollup/rollup-plugin-node-resolve/pull/182) by @sormy)
## 4.1.0 (2019-04-05)
- Add TypeScript typings ([#189](https://github.com/rollup/rollup-plugin-node-resolve/pull/189) by @NotWoods)
- Update dependencies ([#202](https://github.com/rollup/rollup-plugin-node-resolve/pull/202) by @lukastaegert)
## 4.0.1 (2019-02-22)
- Fix issue when external modules are specified in `package.browser` ([#143](https://github.com/rollup/rollup-plugin-node-resolve/pull/143) by @keithamus)
- Fix `package.browser` mapping issue when `false` is specified ([#183](https://github.com/rollup/rollup-plugin-node-resolve/pull/183) by @allex)
## 4.0.0 (2018-12-09)
This release will support rollup@1.0
### Features
- Resolve modules used to define manual chunks ([#185](https://github.com/rollup/rollup-plugin-node-resolve/pull/185) by @mcshaman)
- Update dependencies and plugin hook usage ([#187](https://github.com/rollup/rollup-plugin-node-resolve/pull/187) by @lukastaegert)
## 3.4.0 (2018-09-04)
This release now supports `.mjs` files by default
### Features
- feat: Support .mjs files by default (https://github.com/rollup/rollup-plugin-node-resolve/pull/151, by @leebyron)
## 3.3.0 (2018-03-17)
This release adds the `only` option
### New Features
- feat: add `only` option (#83; @arantes555)
### Docs
- docs: correct description of `jail` option (#120; @GeorgeTaveras1231)
## 3.2.0 (2018-03-07)
This release caches reading/statting of files, to improve speed.
### Performance Improvements
- perf: cache file stats/reads (#126; @keithamus)
## 3.0.4 (unreleased)
- Update lockfile [#137](https://github.com/rollup/rollup-plugin-node-resolve/issues/137)
- Update rollup dependency [#138](https://github.com/rollup/rollup-plugin-node-resolve/issues/138)
- Enable installation from Github [#142](https://github.com/rollup/rollup-plugin-node-resolve/issues/142)
## 3.0.3
- Fix [#130](https://github.com/rollup/rollup-plugin-node-resolve/issues/130) and [#131](https://github.com/rollup/rollup-plugin-node-resolve/issues/131)
## 3.0.2
- Ensure `pkg.browser` is an object if necessary ([#129](https://github.com/rollup/rollup-plugin-node-resolve/pull/129))
## 3.0.1
- Remove `browser-resolve` dependency ([#127](https://github.com/rollup/rollup-plugin-node-resolve/pull/127))
## 3.0.0
- [BREAKING] Remove `options.skip` ([#90](https://github.com/rollup/rollup-plugin-node-resolve/pull/90))
- Add `modulesOnly` option ([#96](https://github.com/rollup/rollup-plugin-node-resolve/pull/96))
## 2.1.1
- Prevent `jail` from breaking builds on Windows ([#93](https://github.com/rollup/rollup-plugin-node-resolve/issues/93))
## 2.1.0
- Add `jail` option ([#53](https://github.com/rollup/rollup-plugin-node-resolve/pull/53))
- Add `customResolveOptions` option ([#79](https://github.com/rollup/rollup-plugin-node-resolve/pull/79))
- Support symlinked packages ([#82](https://github.com/rollup/rollup-plugin-node-resolve/pull/82))
## 2.0.0
- Add support `module` field in package.json as an official alternative to jsnext
## 1.7.3
- Error messages are more descriptive ([#50](https://github.com/rollup/rollup-plugin-node-resolve/issues/50))
## 1.7.2
- Allow entry point paths beginning with ./
## 1.7.1
- Return a `name`
## 1.7.0
- Allow relative IDs to be external ([#32](https://github.com/rollup/rollup-plugin-node-resolve/pull/32))
## 1.6.0
- Skip IDs containing null character
## 1.5.0
- Prefer built-in options, but allow opting out ([#28](https://github.com/rollup/rollup-plugin-node-resolve/pull/28))
## 1.4.0
- Pass `options.extensions` through to `node-resolve`
## 1.3.0
- `skip: true` skips all packages that don't satisfy the `main` or `jsnext` options ([#16](https://github.com/rollup/rollup-plugin-node-resolve/pull/16))
## 1.2.1
- Support scoped packages in `skip` option ([#15](https://github.com/rollup/rollup-plugin-node-resolve/issues/15))
## 1.2.0
- Support `browser` field ([#8](https://github.com/rollup/rollup-plugin-node-resolve/issues/8))
- Get tests to pass on Windows
## 1.1.0
- Use node-resolve to handle various corner cases
## 1.0.0
- Add ES6 build, use Rollup 0.20.0
## 0.1.0
- First release

21
node_modules/@rollup/plugin-node-resolve/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
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.

194
node_modules/@rollup/plugin-node-resolve/README.md generated vendored Executable file
View File

@ -0,0 +1,194 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-node-resolve
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-node-resolve
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-node-resolve
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-node-resolve
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-node-resolve
🍣 A Rollup plugin which locates modules using the [Node resolution algorithm](https://nodejs.org/api/modules.html#modules_all_together), for using third party modules in `node_modules`
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-node-resolve --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import resolve from '@rollup/plugin-node-resolve';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [resolve()]
};
```
Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
## Options
### `browser`
Type: `Boolean`<br>
Default: `false`
If `true`, instructs the plugin to use the `"browser"` property in `package.json` files to specify alternative files to load for bundling. This is useful when bundling for a browser environment. Alternatively, a value of `'browser'` can be added to the `mainFields` option. If `false`, any `"browser"` properties in package files will be ignored. This option takes precedence over `mainFields`.
### `customResolveOptions`
Type: `Boolean`<br>
Default: `null`
An `Object` that specifies additional options that should be passed through to `node-resolve`.
```
customResolveOptions: {
moduleDirectory: 'js_modules'
}
```
### `dedupe`
Type: `Array[...String]`<br>
Default: `[]`
An `Array` of modules names, which instructs the plugin to force resolving for the specified modules to the root `node_modules`. Helps to prevent bundling the same package multiple times if package is imported from dependencies.
```js
dedupe: ['my-package', '@namespace/my-package'];
```
This will deduplicate bare imports such as:
```js
import 'my-package';
import '@namespace/my-package';
```
And it will deduplicate deep imports such as:
```js
import 'my-package/foo.js';
import '@namespace/my-package/bar.js';
```
### `extensions`
Type: `Array[...String]`<br>
Default: `['.mjs', '.js', '.json', '.node']`
Specifies the extensions of files that the plugin will operate on.
### `jail`
Type: `String`<br>
Default: `'/'`
Locks the module search within specified path (e.g. chroot). Modules defined outside this path will be marked as external.
### `mainFields`
Type: `Array[...String]`<br>
Default: `['module', 'main']`<br>
Valid values: `['browser', 'jsnext', 'module', 'main']`
Specifies the properties to scan within a `package.json`, used to determine the bundle entry point. The order of property names is significant, as the first-found property is used as the resolved entry point. If the array contains `'browser'`, key/values specified in the `package.json` `browser` property will be used.
### `only`
DEPRECATED: use "resolveOnly" instead
### `preferBuiltins`
Type: `Boolean`<br>
Default: `true`
If `true`, the plugin will prefer built-in modules (e.g. `fs`, `path`). If `false`, the plugin will look for locally installed modules of the same name.
### `modulesOnly`
Type: `Boolean`<br>
Default: `false`
If `true`, inspect resolved files to assert that they are ES2015 modules.
### `resolveOnly`
Type: `Array[...String|RegExp]`<br>
Default: `null`
An `Array` which instructs the plugin to limit module resolution to those whose names match patterns in the array. _Note: Modules not matching any patterns will be marked as external._
Example: `resolveOnly: ['batman', /^@batcave\/.*$/]`
### `rootDir`
Type: `String`<br>
Default: `process.cwd()`
Specifies the root directory from which to resolve modules. Typically used when resolving entry-point imports, and when resolving deduplicated modules. Useful when executing rollup in a package of a mono-repository.
```
// Set the root directory to be the parent folder
rootDir: path.join(process.cwd(), '..')
```
## Using with @rollup/plugin-commonjs
Since most packages in your node_modules folder are probably legacy CommonJS rather than JavaScript modules, you may need to use [@rollup/plugin-commonjs](https://github.com/rollup/plugins/packages/commonjs):
```js
// rollup.config.js
import resolve from '@rollup/plugin-node-resolve';
import commonjs from '@rollup/plugin-commonjs';
export default {
input: 'main.js',
output: {
file: 'bundle.js',
format: 'iife',
name: 'MyModule'
},
plugins: [resolve(), commonjs()]
};
```
## Resolving Built-Ins (like `fs`)
This plugin won't resolve any builtins (e.g. `fs`). If you need to resolve builtins you can install local modules and set `preferBuiltins` to `false`, or install a plugin like [rollup-plugin-node-polyfills](https://github.com/ionic-team/rollup-plugin-node-polyfills) which provides stubbed versions of these methods.
If you want to silence warnings about builtins, you can add the list of builtins to the `externals` option; like so:
```js
import resolve from '@rollup/plugin-node-resolve';
import builtins from 'builtin-modules'
export default ({
input: ...,
plugins: [resolve()],
external: builtins,
output: ...
})
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View File

@ -0,0 +1,579 @@
import { dirname, resolve, extname, normalize, sep } from 'path';
import builtinList from 'builtin-modules';
import isModule from 'is-module';
import fs, { realpathSync } from 'fs';
import { promisify } from 'util';
import { createFilter } from '@rollup/pluginutils';
import resolveModule from 'resolve';
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
const exists = promisify(fs.exists);
const readFile = promisify(fs.readFile);
const realpath = promisify(fs.realpath);
const stat = promisify(fs.stat);
const onError = error => {
if (error.code === 'ENOENT') {
return false;
}
throw error;
};
const makeCache = fn => {
const cache = new Map();
const wrapped =
/*#__PURE__*/
function () {
var _ref = _asyncToGenerator(function* (param, done) {
if (cache.has(param) === false) {
cache.set(param, fn(param).catch(err => {
cache.delete(param);
throw err;
}));
}
try {
const result = cache.get(param);
const value = yield result;
return done(null, value);
} catch (error) {
return done(error);
}
});
return function wrapped(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
wrapped.clear = () => cache.clear();
return wrapped;
};
const isDirCached = makeCache(
/*#__PURE__*/
function () {
var _ref2 = _asyncToGenerator(function* (file) {
try {
const stats = yield stat(file);
return stats.isDirectory();
} catch (error) {
return onError(error);
}
});
return function (_x3) {
return _ref2.apply(this, arguments);
};
}());
const isFileCached = makeCache(
/*#__PURE__*/
function () {
var _ref3 = _asyncToGenerator(function* (file) {
try {
const stats = yield stat(file);
return stats.isFile();
} catch (error) {
return onError(error);
}
});
return function (_x4) {
return _ref3.apply(this, arguments);
};
}());
const readCachedFile = makeCache(readFile);
const resolveId = promisify(resolveModule); // returns the imported package name for bare module imports
function getPackageName(id) {
if (id.startsWith('.') || id.startsWith('/')) {
return null;
}
const split = id.split('/'); // @my-scope/my-package/foo.js -> @my-scope/my-package
// @my-scope/my-package -> @my-scope/my-package
if (split[0][0] === '@') {
return `${split[0]}/${split[1]}`;
} // my-package/foo.js -> my-package
// my-package -> my-package
return split[0];
}
function getMainFields(options) {
let mainFields;
if (options.mainFields) {
mainFields = options.mainFields;
} else {
mainFields = ['module', 'main'];
}
if (options.browser && mainFields.indexOf('browser') === -1) {
return ['browser'].concat(mainFields);
}
if (!mainFields.length) {
throw new Error('Please ensure at least one `mainFields` value is specified');
}
return mainFields;
}
function getPackageInfo(options) {
const cache = options.cache,
extensions = options.extensions,
pkg = options.pkg,
mainFields = options.mainFields,
preserveSymlinks = options.preserveSymlinks,
useBrowserOverrides = options.useBrowserOverrides;
let pkgPath = options.pkgPath;
if (cache.has(pkgPath)) {
return cache.get(pkgPath);
} // browserify/resolve doesn't realpath paths returned in its packageFilter callback
if (!preserveSymlinks) {
pkgPath = realpathSync(pkgPath);
}
const pkgRoot = dirname(pkgPath);
const packageInfo = {
// copy as we are about to munge the `main` field of `pkg`.
packageJson: Object.assign({}, pkg),
// path to package.json file
packageJsonPath: pkgPath,
// directory containing the package.json
root: pkgRoot,
// which main field was used during resolution of this module (main, module, or browser)
resolvedMainField: 'main',
// whether the browser map was used to resolve the entry point to this module
browserMappedMain: false,
// the entry point of the module with respect to the selected main field and any
// relevant browser mappings.
resolvedEntryPoint: ''
};
let overriddenMain = false;
for (let i = 0; i < mainFields.length; i++) {
const field = mainFields[i];
if (typeof pkg[field] === 'string') {
pkg.main = pkg[field];
packageInfo.resolvedMainField = field;
overriddenMain = true;
break;
}
}
const internalPackageInfo = {
cachedPkg: pkg,
hasModuleSideEffects: () => null,
hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
packageBrowserField: useBrowserOverrides && typeof pkg.browser === 'object' && Object.keys(pkg.browser).reduce((browser, key) => {
let resolved = pkg.browser[key];
if (resolved && resolved[0] === '.') {
resolved = resolve(pkgRoot, resolved);
}
/* eslint-disable no-param-reassign */
browser[key] = resolved;
if (key[0] === '.') {
const absoluteKey = resolve(pkgRoot, key);
browser[absoluteKey] = resolved;
if (!extname(key)) {
extensions.reduce((subBrowser, ext) => {
subBrowser[absoluteKey + ext] = subBrowser[key];
return subBrowser;
}, browser);
}
}
return browser;
}, {}),
packageInfo
};
const browserMap = internalPackageInfo.packageBrowserField;
if (useBrowserOverrides && typeof pkg.browser === 'object' && // eslint-disable-next-line no-prototype-builtins
browserMap.hasOwnProperty(pkg.main)) {
packageInfo.resolvedEntryPoint = browserMap[pkg.main];
packageInfo.browserMappedMain = true;
} else {
// index.node is technically a valid default entrypoint as well...
packageInfo.resolvedEntryPoint = resolve(pkgRoot, pkg.main || 'index.js');
packageInfo.browserMappedMain = false;
}
const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
internalPackageInfo.hasModuleSideEffects = createFilter(packageSideEffects, null, {
resolve: pkgRoot
});
}
cache.set(pkgPath, internalPackageInfo);
return internalPackageInfo;
}
function normalizeInput(input) {
if (Array.isArray(input)) {
return input;
} else if (typeof input === 'object') {
return Object.values(input);
} // otherwise it's a string
return input;
} // Resolve module specifiers in order. Promise resolves to the first module that resolves
// successfully, or the error that resulted from the last attempted module resolution.
function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
let promise = Promise.resolve();
for (let i = 0; i < importSpecifierList.length; i++) {
promise = promise.then(value => {
// if we've already resolved to something, just return it.
if (value) {
return value;
}
return resolveId(importSpecifierList[i], resolveOptions);
});
if (i < importSpecifierList.length - 1) {
// swallow MODULE_NOT_FOUND errors from all but the last resolution
promise = promise.catch(error => {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
});
}
}
return promise;
}
const builtins = new Set(builtinList);
const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
const nullFn = () => null;
const defaults = {
customResolveOptions: {},
dedupe: [],
// It's important that .mjs is listed before .js so that Rollup will interpret npm modules
// which deploy both ESM .mjs and CommonJS .js files as ESM.
extensions: ['.mjs', '.js', '.json', '.node'],
resolveOnly: []
};
function nodeResolve(opts = {}) {
const options = Object.assign({}, defaults, opts);
const customResolveOptions = options.customResolveOptions,
extensions = options.extensions,
jail = options.jail;
const warnings = [];
const packageInfoCache = new Map();
const idToPackageInfo = new Map();
const mainFields = getMainFields(options);
const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
const rootDir = options.rootDir || process.cwd();
let dedupe = options.dedupe;
let rollupOptions;
if (options.only) {
warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
options.resolveOnly = options.only;
}
if (typeof dedupe !== 'function') {
dedupe = importee => options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
}
const resolveOnly = options.resolveOnly.map(pattern => {
if (pattern instanceof RegExp) {
return pattern;
}
const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
return new RegExp(`^${normalized}$`);
});
const browserMapCache = new Map();
let preserveSymlinks;
return {
name: 'node-resolve',
buildStart(options) {
rollupOptions = options;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = warnings[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const warning = _step.value;
this.warn(warning);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
preserveSymlinks = options.preserveSymlinks;
},
generateBundle() {
readCachedFile.clear();
isFileCached.clear();
isDirCached.clear();
},
resolveId(importee, importer) {
var _this = this;
return _asyncToGenerator(function* () {
if (importee === ES6_BROWSER_EMPTY) {
return importee;
} // ignore IDs with null character, these belong to other plugins
if (/\0/.test(importee)) return null;
const basedir = !importer || dedupe(importee) ? rootDir : dirname(importer); // https://github.com/defunctzombie/package-browser-field-spec
const browser = browserMapCache.get(importer);
if (useBrowserOverrides && browser) {
const resolvedImportee = resolve(basedir, importee);
if (browser[importee] === false || browser[resolvedImportee] === false) {
return ES6_BROWSER_EMPTY;
}
const browserImportee = browser[importee] || browser[resolvedImportee] || browser[`${resolvedImportee}.js`] || browser[`${resolvedImportee}.json`];
if (browserImportee) {
importee = browserImportee;
}
}
const parts = importee.split(/[/\\]/);
let id = parts.shift();
if (id[0] === '@' && parts.length > 0) {
// scoped packages
id += `/${parts.shift()}`;
} else if (id[0] === '.') {
// an import relative to the parent dir of the importer
id = resolve(basedir, importee);
}
const input = normalizeInput(rollupOptions.input);
if (resolveOnly.length && !resolveOnly.some(pattern => pattern.test(id))) {
if (input.includes(id)) {
return null;
}
return false;
}
let hasModuleSideEffects = nullFn;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides
});
packageInfo = info.packageInfo;
hasModuleSideEffects = info.hasModuleSideEffects;
hasPackageEntry = info.hasPackageEntry;
packageBrowserField = info.packageBrowserField;
return info.cachedPkg;
};
let resolveOptions = {
basedir,
packageFilter: filter,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions
};
if (preserveSymlinks !== undefined) {
resolveOptions.preserveSymlinks = preserveSymlinks;
}
const importSpecifierList = [];
if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
// For module graph roots (i.e. when importer is undefined), we
// need to handle 'path fragments` like `foo/bar` that are commonly
// found in rollup config files. If importee doesn't look like a
// relative or absolute path, we make it relative and attempt to
// resolve it. If we don't find anything, we try resolving it as we
// got it.
importSpecifierList.push(`./${importee}`);
}
const importeeIsBuiltin = builtins.has(importee);
if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
// The `resolve` library will not resolve packages with the same
// name as a node built-in module. If we're resolving something
// that's a builtin, and we don't prefer to find built-ins, we
// first try to look up a local module with that name. If we don't
// find anything, we resolve the builtin which just returns back
// the built-in's name.
importSpecifierList.push(`${importee}/`);
}
importSpecifierList.push(importee);
resolveOptions = Object.assign(resolveOptions, customResolveOptions);
try {
let resolved = yield resolveImportSpecifiers(importSpecifierList, resolveOptions);
if (resolved && packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
if (!packageBrowserField[resolved]) {
browserMapCache.set(resolved, packageBrowserField);
return ES6_BROWSER_EMPTY;
}
resolved = packageBrowserField[resolved];
}
browserMapCache.set(resolved, packageBrowserField);
}
if (hasPackageEntry && !preserveSymlinks && resolved) {
const fileExists = yield exists(resolved);
if (fileExists) {
resolved = yield realpath(resolved);
}
}
idToPackageInfo.set(resolved, packageInfo);
if (hasPackageEntry) {
if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
return null;
} else if (importeeIsBuiltin && preferBuiltins) {
if (!isPreferBuiltinsSet) {
_this.warn(`preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`);
}
return null;
} else if (jail && resolved.indexOf(normalize(jail.trim(sep))) !== 0) {
return null;
}
}
if (resolved && options.modulesOnly) {
const code = yield readFile(resolved, 'utf-8');
if (isModule(code)) {
return {
id: resolved,
moduleSideEffects: hasModuleSideEffects(resolved)
};
}
return null;
}
const result = {
id: resolved,
moduleSideEffects: hasModuleSideEffects(resolved)
};
return result;
} catch (error) {
return null;
}
})();
},
load(importee) {
if (importee === ES6_BROWSER_EMPTY) {
return 'export default {};';
}
return null;
},
getPackageInfoForId(id) {
return idToPackageInfo.get(id);
}
};
}
export default nodeResolve;

584
node_modules/@rollup/plugin-node-resolve/dist/index.js generated vendored Normal file
View File

@ -0,0 +1,584 @@
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var path = require('path');
var builtinList = _interopDefault(require('builtin-modules'));
var isModule = _interopDefault(require('is-module'));
var fs = require('fs');
var fs__default = _interopDefault(fs);
var util = require('util');
var pluginutils = require('@rollup/pluginutils');
var resolveModule = _interopDefault(require('resolve'));
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) {
try {
var info = gen[key](arg);
var value = info.value;
} catch (error) {
reject(error);
return;
}
if (info.done) {
resolve(value);
} else {
Promise.resolve(value).then(_next, _throw);
}
}
function _asyncToGenerator(fn) {
return function () {
var self = this,
args = arguments;
return new Promise(function (resolve, reject) {
var gen = fn.apply(self, args);
function _next(value) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value);
}
function _throw(err) {
asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err);
}
_next(undefined);
});
};
}
const exists = util.promisify(fs__default.exists);
const readFile = util.promisify(fs__default.readFile);
const realpath = util.promisify(fs__default.realpath);
const stat = util.promisify(fs__default.stat);
const onError = error => {
if (error.code === 'ENOENT') {
return false;
}
throw error;
};
const makeCache = fn => {
const cache = new Map();
const wrapped =
/*#__PURE__*/
function () {
var _ref = _asyncToGenerator(function* (param, done) {
if (cache.has(param) === false) {
cache.set(param, fn(param).catch(err => {
cache.delete(param);
throw err;
}));
}
try {
const result = cache.get(param);
const value = yield result;
return done(null, value);
} catch (error) {
return done(error);
}
});
return function wrapped(_x, _x2) {
return _ref.apply(this, arguments);
};
}();
wrapped.clear = () => cache.clear();
return wrapped;
};
const isDirCached = makeCache(
/*#__PURE__*/
function () {
var _ref2 = _asyncToGenerator(function* (file) {
try {
const stats = yield stat(file);
return stats.isDirectory();
} catch (error) {
return onError(error);
}
});
return function (_x3) {
return _ref2.apply(this, arguments);
};
}());
const isFileCached = makeCache(
/*#__PURE__*/
function () {
var _ref3 = _asyncToGenerator(function* (file) {
try {
const stats = yield stat(file);
return stats.isFile();
} catch (error) {
return onError(error);
}
});
return function (_x4) {
return _ref3.apply(this, arguments);
};
}());
const readCachedFile = makeCache(readFile);
const resolveId = util.promisify(resolveModule); // returns the imported package name for bare module imports
function getPackageName(id) {
if (id.startsWith('.') || id.startsWith('/')) {
return null;
}
const split = id.split('/'); // @my-scope/my-package/foo.js -> @my-scope/my-package
// @my-scope/my-package -> @my-scope/my-package
if (split[0][0] === '@') {
return `${split[0]}/${split[1]}`;
} // my-package/foo.js -> my-package
// my-package -> my-package
return split[0];
}
function getMainFields(options) {
let mainFields;
if (options.mainFields) {
mainFields = options.mainFields;
} else {
mainFields = ['module', 'main'];
}
if (options.browser && mainFields.indexOf('browser') === -1) {
return ['browser'].concat(mainFields);
}
if (!mainFields.length) {
throw new Error('Please ensure at least one `mainFields` value is specified');
}
return mainFields;
}
function getPackageInfo(options) {
const cache = options.cache,
extensions = options.extensions,
pkg = options.pkg,
mainFields = options.mainFields,
preserveSymlinks = options.preserveSymlinks,
useBrowserOverrides = options.useBrowserOverrides;
let pkgPath = options.pkgPath;
if (cache.has(pkgPath)) {
return cache.get(pkgPath);
} // browserify/resolve doesn't realpath paths returned in its packageFilter callback
if (!preserveSymlinks) {
pkgPath = fs.realpathSync(pkgPath);
}
const pkgRoot = path.dirname(pkgPath);
const packageInfo = {
// copy as we are about to munge the `main` field of `pkg`.
packageJson: Object.assign({}, pkg),
// path to package.json file
packageJsonPath: pkgPath,
// directory containing the package.json
root: pkgRoot,
// which main field was used during resolution of this module (main, module, or browser)
resolvedMainField: 'main',
// whether the browser map was used to resolve the entry point to this module
browserMappedMain: false,
// the entry point of the module with respect to the selected main field and any
// relevant browser mappings.
resolvedEntryPoint: ''
};
let overriddenMain = false;
for (let i = 0; i < mainFields.length; i++) {
const field = mainFields[i];
if (typeof pkg[field] === 'string') {
pkg.main = pkg[field];
packageInfo.resolvedMainField = field;
overriddenMain = true;
break;
}
}
const internalPackageInfo = {
cachedPkg: pkg,
hasModuleSideEffects: () => null,
hasPackageEntry: overriddenMain !== false || mainFields.indexOf('main') !== -1,
packageBrowserField: useBrowserOverrides && typeof pkg.browser === 'object' && Object.keys(pkg.browser).reduce((browser, key) => {
let resolved = pkg.browser[key];
if (resolved && resolved[0] === '.') {
resolved = path.resolve(pkgRoot, resolved);
}
/* eslint-disable no-param-reassign */
browser[key] = resolved;
if (key[0] === '.') {
const absoluteKey = path.resolve(pkgRoot, key);
browser[absoluteKey] = resolved;
if (!path.extname(key)) {
extensions.reduce((subBrowser, ext) => {
subBrowser[absoluteKey + ext] = subBrowser[key];
return subBrowser;
}, browser);
}
}
return browser;
}, {}),
packageInfo
};
const browserMap = internalPackageInfo.packageBrowserField;
if (useBrowserOverrides && typeof pkg.browser === 'object' && // eslint-disable-next-line no-prototype-builtins
browserMap.hasOwnProperty(pkg.main)) {
packageInfo.resolvedEntryPoint = browserMap[pkg.main];
packageInfo.browserMappedMain = true;
} else {
// index.node is technically a valid default entrypoint as well...
packageInfo.resolvedEntryPoint = path.resolve(pkgRoot, pkg.main || 'index.js');
packageInfo.browserMappedMain = false;
}
const packageSideEffects = pkg.sideEffects;
if (typeof packageSideEffects === 'boolean') {
internalPackageInfo.hasModuleSideEffects = () => packageSideEffects;
} else if (Array.isArray(packageSideEffects)) {
internalPackageInfo.hasModuleSideEffects = pluginutils.createFilter(packageSideEffects, null, {
resolve: pkgRoot
});
}
cache.set(pkgPath, internalPackageInfo);
return internalPackageInfo;
}
function normalizeInput(input) {
if (Array.isArray(input)) {
return input;
} else if (typeof input === 'object') {
return Object.values(input);
} // otherwise it's a string
return input;
} // Resolve module specifiers in order. Promise resolves to the first module that resolves
// successfully, or the error that resulted from the last attempted module resolution.
function resolveImportSpecifiers(importSpecifierList, resolveOptions) {
let promise = Promise.resolve();
for (let i = 0; i < importSpecifierList.length; i++) {
promise = promise.then(value => {
// if we've already resolved to something, just return it.
if (value) {
return value;
}
return resolveId(importSpecifierList[i], resolveOptions);
});
if (i < importSpecifierList.length - 1) {
// swallow MODULE_NOT_FOUND errors from all but the last resolution
promise = promise.catch(error => {
if (error.code !== 'MODULE_NOT_FOUND') {
throw error;
}
});
}
}
return promise;
}
const builtins = new Set(builtinList);
const ES6_BROWSER_EMPTY = '\0node-resolve:empty.js';
const nullFn = () => null;
const defaults = {
customResolveOptions: {},
dedupe: [],
// It's important that .mjs is listed before .js so that Rollup will interpret npm modules
// which deploy both ESM .mjs and CommonJS .js files as ESM.
extensions: ['.mjs', '.js', '.json', '.node'],
resolveOnly: []
};
function nodeResolve(opts = {}) {
const options = Object.assign({}, defaults, opts);
const customResolveOptions = options.customResolveOptions,
extensions = options.extensions,
jail = options.jail;
const warnings = [];
const packageInfoCache = new Map();
const idToPackageInfo = new Map();
const mainFields = getMainFields(options);
const useBrowserOverrides = mainFields.indexOf('browser') !== -1;
const isPreferBuiltinsSet = options.preferBuiltins === true || options.preferBuiltins === false;
const preferBuiltins = isPreferBuiltinsSet ? options.preferBuiltins : true;
const rootDir = options.rootDir || process.cwd();
let dedupe = options.dedupe;
let rollupOptions;
if (options.only) {
warnings.push('node-resolve: The `only` options is deprecated, please use `resolveOnly`');
options.resolveOnly = options.only;
}
if (typeof dedupe !== 'function') {
dedupe = importee => options.dedupe.includes(importee) || options.dedupe.includes(getPackageName(importee));
}
const resolveOnly = options.resolveOnly.map(pattern => {
if (pattern instanceof RegExp) {
return pattern;
}
const normalized = pattern.replace(/[\\^$*+?.()|[\]{}]/g, '\\$&');
return new RegExp(`^${normalized}$`);
});
const browserMapCache = new Map();
let preserveSymlinks;
return {
name: 'node-resolve',
buildStart(options) {
rollupOptions = options;
var _iteratorNormalCompletion = true;
var _didIteratorError = false;
var _iteratorError = undefined;
try {
for (var _iterator = warnings[Symbol.iterator](), _step; !(_iteratorNormalCompletion = (_step = _iterator.next()).done); _iteratorNormalCompletion = true) {
const warning = _step.value;
this.warn(warning);
}
} catch (err) {
_didIteratorError = true;
_iteratorError = err;
} finally {
try {
if (!_iteratorNormalCompletion && _iterator.return != null) {
_iterator.return();
}
} finally {
if (_didIteratorError) {
throw _iteratorError;
}
}
}
preserveSymlinks = options.preserveSymlinks;
},
generateBundle() {
readCachedFile.clear();
isFileCached.clear();
isDirCached.clear();
},
resolveId(importee, importer) {
var _this = this;
return _asyncToGenerator(function* () {
if (importee === ES6_BROWSER_EMPTY) {
return importee;
} // ignore IDs with null character, these belong to other plugins
if (/\0/.test(importee)) return null;
const basedir = !importer || dedupe(importee) ? rootDir : path.dirname(importer); // https://github.com/defunctzombie/package-browser-field-spec
const browser = browserMapCache.get(importer);
if (useBrowserOverrides && browser) {
const resolvedImportee = path.resolve(basedir, importee);
if (browser[importee] === false || browser[resolvedImportee] === false) {
return ES6_BROWSER_EMPTY;
}
const browserImportee = browser[importee] || browser[resolvedImportee] || browser[`${resolvedImportee}.js`] || browser[`${resolvedImportee}.json`];
if (browserImportee) {
importee = browserImportee;
}
}
const parts = importee.split(/[/\\]/);
let id = parts.shift();
if (id[0] === '@' && parts.length > 0) {
// scoped packages
id += `/${parts.shift()}`;
} else if (id[0] === '.') {
// an import relative to the parent dir of the importer
id = path.resolve(basedir, importee);
}
const input = normalizeInput(rollupOptions.input);
if (resolveOnly.length && !resolveOnly.some(pattern => pattern.test(id))) {
if (input.includes(id)) {
return null;
}
return false;
}
let hasModuleSideEffects = nullFn;
let hasPackageEntry = true;
let packageBrowserField = false;
let packageInfo;
const filter = (pkg, pkgPath) => {
const info = getPackageInfo({
cache: packageInfoCache,
extensions,
pkg,
pkgPath,
mainFields,
preserveSymlinks,
useBrowserOverrides
});
packageInfo = info.packageInfo;
hasModuleSideEffects = info.hasModuleSideEffects;
hasPackageEntry = info.hasPackageEntry;
packageBrowserField = info.packageBrowserField;
return info.cachedPkg;
};
let resolveOptions = {
basedir,
packageFilter: filter,
readFile: readCachedFile,
isFile: isFileCached,
isDirectory: isDirCached,
extensions
};
if (preserveSymlinks !== undefined) {
resolveOptions.preserveSymlinks = preserveSymlinks;
}
const importSpecifierList = [];
if (importer === undefined && !importee[0].match(/^\.?\.?\//)) {
// For module graph roots (i.e. when importer is undefined), we
// need to handle 'path fragments` like `foo/bar` that are commonly
// found in rollup config files. If importee doesn't look like a
// relative or absolute path, we make it relative and attempt to
// resolve it. If we don't find anything, we try resolving it as we
// got it.
importSpecifierList.push(`./${importee}`);
}
const importeeIsBuiltin = builtins.has(importee);
if (importeeIsBuiltin && (!preferBuiltins || !isPreferBuiltinsSet)) {
// The `resolve` library will not resolve packages with the same
// name as a node built-in module. If we're resolving something
// that's a builtin, and we don't prefer to find built-ins, we
// first try to look up a local module with that name. If we don't
// find anything, we resolve the builtin which just returns back
// the built-in's name.
importSpecifierList.push(`${importee}/`);
}
importSpecifierList.push(importee);
resolveOptions = Object.assign(resolveOptions, customResolveOptions);
try {
let resolved = yield resolveImportSpecifiers(importSpecifierList, resolveOptions);
if (resolved && packageBrowserField) {
if (Object.prototype.hasOwnProperty.call(packageBrowserField, resolved)) {
if (!packageBrowserField[resolved]) {
browserMapCache.set(resolved, packageBrowserField);
return ES6_BROWSER_EMPTY;
}
resolved = packageBrowserField[resolved];
}
browserMapCache.set(resolved, packageBrowserField);
}
if (hasPackageEntry && !preserveSymlinks && resolved) {
const fileExists = yield exists(resolved);
if (fileExists) {
resolved = yield realpath(resolved);
}
}
idToPackageInfo.set(resolved, packageInfo);
if (hasPackageEntry) {
if (builtins.has(resolved) && preferBuiltins && isPreferBuiltinsSet) {
return null;
} else if (importeeIsBuiltin && preferBuiltins) {
if (!isPreferBuiltinsSet) {
_this.warn(`preferring built-in module '${importee}' over local alternative at '${resolved}', pass 'preferBuiltins: false' to disable this behavior or 'preferBuiltins: true' to disable this warning`);
}
return null;
} else if (jail && resolved.indexOf(path.normalize(jail.trim(path.sep))) !== 0) {
return null;
}
}
if (resolved && options.modulesOnly) {
const code = yield readFile(resolved, 'utf-8');
if (isModule(code)) {
return {
id: resolved,
moduleSideEffects: hasModuleSideEffects(resolved)
};
}
return null;
}
const result = {
id: resolved,
moduleSideEffects: hasModuleSideEffects(resolved)
};
return result;
} catch (error) {
return null;
}
})();
},
load(importee) {
if (importee === ES6_BROWSER_EMPTY) {
return 'export default {};';
}
return null;
},
getPackageInfoForId(id) {
return idToPackageInfo.get(id);
}
};
}
module.exports = nodeResolve;

113
node_modules/@rollup/plugin-node-resolve/package.json generated vendored Normal file
View File

@ -0,0 +1,113 @@
{
"_from": "@rollup/plugin-node-resolve",
"_id": "@rollup/plugin-node-resolve@7.1.1",
"_inBundle": false,
"_integrity": "sha512-14ddhD7TnemeHE97a4rLOhobfYvUVcaYuqTnL8Ti7Jxi9V9Jr5LY7Gko4HZ5k4h4vqQM0gBQt6tsp9xXW94WPA==",
"_location": "/@rollup/plugin-node-resolve",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "@rollup/plugin-node-resolve",
"name": "@rollup/plugin-node-resolve",
"escapedName": "@rollup%2fplugin-node-resolve",
"scope": "@rollup",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/@rollup/plugin-node-resolve/-/plugin-node-resolve-7.1.1.tgz",
"_shasum": "8c6e59c4b28baf9d223028d0e450e06a485bb2b7",
"_spec": "@rollup/plugin-node-resolve",
"_where": "/home/juan/bigint-crypto-utils",
"author": {
"name": "Rich Harris",
"email": "richard.a.harris@gmail.com"
},
"ava": {
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"bundleDependencies": false,
"dependencies": {
"@rollup/pluginutils": "^3.0.6",
"@types/resolve": "0.0.8",
"builtin-modules": "^3.1.0",
"is-module": "^1.0.0",
"resolve": "^1.14.2"
},
"deprecated": false,
"description": "Locate and bundle third-party dependencies in node_modules",
"devDependencies": {
"@babel/core": "^7.8.3",
"@babel/preset-env": "^7.8.3",
"@rollup/plugin-json": "^4.0.1",
"es5-ext": "^0.10.53",
"rollup": "^1.29.0",
"rollup-plugin-babel": "^4.3.3",
"rollup-plugin-commonjs": "^10.1.0",
"source-map": "^0.7.3",
"string-capitalize": "^1.0.1"
},
"engines": {
"node": ">= 8.0.0"
},
"files": [
"dist",
"types",
"README.md",
"LICENSE"
],
"homepage": "https://github.com/rollup/plugins/tree/master/packages/node-resolve/#readme",
"keywords": [
"rollup",
"plugin",
"es2015",
"npm",
"modules"
],
"license": "MIT",
"main": "dist/index.js",
"module": "dist/index.es.js",
"name": "@rollup/plugin-node-resolve",
"peerDependencies": {
"rollup": "^1.20.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/plugins.git"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm run test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm run build && pnpm run lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm run test -- --verbose && pnpm run test:ts",
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
"lint:docs": "prettier --single-quote --write README.md",
"lint:js": "eslint --fix --cache src test",
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
"prebuild": "del-cli dist",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run lint && pnpm run test && pnpm run test:ts",
"pretest": "pnpm run build",
"test": "ava",
"test:ts": "tsc types/index.d.ts test/types.ts --noEmit"
},
"types": "types/index.d.ts",
"version": "7.1.1"
}

84
node_modules/@rollup/plugin-node-resolve/types/index.d.ts generated vendored Executable file
View File

@ -0,0 +1,84 @@
import { Plugin } from 'rollup';
import { AsyncOpts } from 'resolve';
export interface Options {
/**
* If `true`, instructs the plugin to use the `"browser"` property in `package.json`
* files to specify alternative files to load for bundling. This is useful when
* bundling for a browser environment. Alternatively, a value of `'browser'` can be
* added to the `mainFields` option. If `false`, any `"browser"` properties in
* package files will be ignored. This option takes precedence over `mainFields`.
* @default false
*/
browser?: boolean;
/**
* An `Object` that specifies additional options that should be passed through to `node-resolve`.
*/
customResolveOptions?: AsyncOpts;
/**
* An `Array` of modules names, which instructs the plugin to force resolving for the
* specified modules to the root `node_modules`. Helps to prevent bundling the same
* package multiple times if package is imported from dependencies.
*/
dedupe?: string[] | ((importee: string) => boolean);
/**
* Specifies the extensions of files that the plugin will operate on.
* @default [ '.mjs', '.js', '.json', '.node' ]
*/
extensions?: ReadonlyArray<string>;
/**
* Locks the module search within specified path (e.g. chroot). Modules defined
* outside this path will be marked as external.
* @default '/'
*/
jail?: string;
/**
* Specifies the properties to scan within a `package.json`, used to determine the
* bundle entry point.
* @default ['module', 'main']
*/
mainFields?: ReadonlyArray<string>;
/**
* If `true`, inspect resolved files to assert that they are ES2015 modules.
* @default false
*/
modulesOnly?: boolean;
/**
* @deprecated use "resolveOnly" instead
* @default null
*/
only?: ReadonlyArray<string | RegExp> | null;
/**
* If `true`, the plugin will prefer built-in modules (e.g. `fs`, `path`). If `false`,
* the plugin will look for locally installed modules of the same name.
* @default true
*/
preferBuiltins?: boolean;
/**
* An `Array` which instructs the plugin to limit module resolution to those whose
* names match patterns in the array.
* @default []
*/
resolveOnly?: ReadonlyArray<string | RegExp> | null;
/**
* Specifies the root directory from which to resolve modules. Typically used when
* resolving entry-point imports, and when resolving deduplicated modules.
* @default process.cwd()
*/
rootDir?: string;
}
/**
* Locate modules using the Node resolution algorithm, for using third party modules in node_modules
*/
export default function nodeResolve(options?: Options): Plugin;

70
node_modules/@rollup/plugin-replace/CHANGELOG.md generated vendored Executable file
View File

@ -0,0 +1,70 @@
# @rollup/plugin-replace ChangeLog
## v2.3.1
_2020-02-01_
### Updates
- chore: update dependencies (aca4a94)
## 2.3.0
_2019-12-21_
- feat(replace): allow plugin to operate as an output plugin (#55)
## 2.2.1
_2019-11-06_
- Move `typescript` to `devDependencies`
## 2.2.0
_2019-04-10_
- Add index.d.ts typings file ([#31](https://github.com/rollup/rollup-plugin-replace/pull/31))
## 2.1.1
_2019-03-18_
- Update rollup-pluginutils ([#29](https://github.com/rollup/rollup-plugin-replace/pull/29))
- Update dependencies ([#30](https://github.com/rollup/rollup-plugin-replace/pull/30))
## 2.1.0
_2018-10-07_
- Do not mutate values passed as option ([#22](https://github.com/rollup/rollup-plugin-replace/pull/22))
- Update dependencies and improve tests ([#26](https://github.com/rollup/rollup-plugin-replace/pull/26))
## 2.0.0
- Only match on word boundaries, unless delimiters are empty strings ([#10](https://github.com/rollup/rollup-plugin-replace/pull/10))
## 1.2.1
- Match longest keys first ([#8](https://github.com/rollup/rollup-plugin-replace/pull/8))
- Escape keys ([#9](https://github.com/rollup/rollup-plugin-replace/pull/9))
## 1.2.0
- Allow replacement to be a function that takes a module ID ([#1](https://github.com/rollup/rollup-plugin-replace/issues/1))
## 1.1.1
- Return a `name`
## 1.1.0
- Generate sourcemaps by default
## 1.0.1
- Include correct files in package
## 1.0.0
- First release

21
node_modules/@rollup/plugin-replace/LICENSE generated vendored Normal file
View File

@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2019 RollupJS Plugin Contributors (https://github.com/rollup/plugins/graphs/contributors)
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.

119
node_modules/@rollup/plugin-replace/README.md generated vendored Normal file
View File

@ -0,0 +1,119 @@
[npm]: https://img.shields.io/npm/v/@rollup/plugin-replace
[npm-url]: https://www.npmjs.com/package/@rollup/plugin-replace
[size]: https://packagephobia.now.sh/badge?p=@rollup/plugin-replace
[size-url]: https://packagephobia.now.sh/result?p=@rollup/plugin-replace
[![npm][npm]][npm-url]
[![size][size]][size-url]
[![libera manifesto](https://img.shields.io/badge/libera-manifesto-lightgrey.svg)](https://liberamanifesto.com)
# @rollup/plugin-replace
🍣 A Rollup plugin which replaces strings in files while bundling.
## Requirements
This plugin requires an [LTS](https://github.com/nodejs/Release) Node version (v8.0.0+) and Rollup v1.20.0+.
## Install
Using npm:
```console
npm install @rollup/plugin-replace --save-dev
```
## Usage
Create a `rollup.config.js` [configuration file](https://www.rollupjs.org/guide/en/#configuration-files) and import the plugin:
```js
import replace from '@rollup/plugin-replace';
export default {
input: 'src/index.js',
output: {
dir: 'output',
format: 'cjs'
},
plugins: [replace({ __buildEnv__: 'production' })]
};
```
Then call `rollup` either via the [CLI](https://www.rollupjs.org/guide/en/#command-line-reference) or the [API](https://www.rollupjs.org/guide/en/#javascript-api).
The configuration above will replace every instance of `__buildEnv__` with `'production'` in any file included in the build. _Note: Values should always be strings. For complex values, use `JSON.stringify`._
Typically, `@rollup/plugin-replace` should be placed in `plugins` _before_ other plugins so that they may apply optimizations, such as dead code removal.
## Options
In addition to the properties and values specified for replacement, users may also specify the options below.
### `delimiters`
Type: `Array[...String, String]`<br>
Default: `['\b', '\b']`
Specifies the boundaries around which strings will be replaced. By default, delimiters are [word boundaries](https://www.regular-expressions.info/wordboundaries.html). See [Word Boundaries](#word-boundaries) below for more information.
### `exclude`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should _ignore_. By default no files are ignored.
### `include`
Type: `String` | `Array[...String]`<br>
Default: `null`
A [minimatch pattern](https://github.com/isaacs/minimatch), or array of patterns, which specifies the files in the build the plugin should operate on. By default all files are targeted.
## Word Boundaries
By default, values will only match if they are surrounded by _word boundaries_.
Consider the following options and build file:
```js
module.exports = {
...
plugins: [replace({ changed: 'replaced' })]
};
```
```js
// file.js
console.log('changed');
console.log('unchanged');
```
The result would be:
```js
// file.js
console.log('replaced');
console.log('unchanged');
```
To ignore word boundaries and replace every instance of the string, wherever it may be, specify empty strings as delimiters:
```js
export default {
...
plugins: [
replace({
changed: 'replaced',
delimiters: ['', '']
})
]
};
```
## Meta
[CONTRIBUTING](/.github/CONTRIBUTING.md)
[LICENSE (MIT)](/LICENSE)

View File

@ -0,0 +1,106 @@
'use strict';
function _interopDefault (ex) { return (ex && (typeof ex === 'object') && 'default' in ex) ? ex['default'] : ex; }
var MagicString = _interopDefault(require('magic-string'));
var pluginutils = require('@rollup/pluginutils');
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
function ensureFunction(functionOrValue) {
if (typeof functionOrValue === 'function') { return functionOrValue; }
return function () { return functionOrValue; };
}
function longest(a, b) {
return b.length - a.length;
}
function getReplacements(options) {
if (options.values) {
return Object.assign({}, options.values);
}
var values = Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
delete values.sourcemap;
delete values.sourceMap;
return values;
}
function mapToFunctions(object) {
return Object.keys(object).reduce(function (fns, key) {
var functions = Object.assign({}, fns);
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}
function replace(options) {
if ( options === void 0 ) options = {};
var filter = pluginutils.createFilter(options.include, options.exclude);
var delimiters = options.delimiters;
var functionValues = mapToFunctions(getReplacements(options));
var keys = Object.keys(functionValues)
.sort(longest)
.map(escape);
var pattern = delimiters
? new RegExp(((escape(delimiters[0])) + "(" + (keys.join('|')) + ")" + (escape(delimiters[1]))), 'g')
: new RegExp(("\\b(" + (keys.join('|')) + ")\\b"), 'g');
return {
name: 'replace',
renderChunk: function renderChunk(code, chunk) {
var id = chunk.fileName;
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
},
transform: function transform(code, id) {
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
}
};
function executeReplacement(code, id) {
var magicString = new MagicString(code);
if (!codeHasReplacements(code, id, magicString)) {
return null;
}
var result = { code: magicString.toString() };
if (isSourceMapEnabled()) {
result.map = magicString.generateMap({ hires: true });
}
return result;
}
function codeHasReplacements(code, id, magicString) {
var result = false;
var match;
// eslint-disable-next-line no-cond-assign
while ((match = pattern.exec(code))) {
result = true;
var start = match.index;
var end = start + match[0].length;
var replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
return result;
}
function isSourceMapEnabled() {
return options.sourceMap !== false && options.sourcemap !== false;
}
}
module.exports = replace;

View File

@ -0,0 +1,102 @@
import MagicString from 'magic-string';
import { createFilter } from '@rollup/pluginutils';
function escape(str) {
return str.replace(/[-[\]/{}()*+?.\\^$|]/g, '\\$&');
}
function ensureFunction(functionOrValue) {
if (typeof functionOrValue === 'function') { return functionOrValue; }
return function () { return functionOrValue; };
}
function longest(a, b) {
return b.length - a.length;
}
function getReplacements(options) {
if (options.values) {
return Object.assign({}, options.values);
}
var values = Object.assign({}, options);
delete values.delimiters;
delete values.include;
delete values.exclude;
delete values.sourcemap;
delete values.sourceMap;
return values;
}
function mapToFunctions(object) {
return Object.keys(object).reduce(function (fns, key) {
var functions = Object.assign({}, fns);
functions[key] = ensureFunction(object[key]);
return functions;
}, {});
}
function replace(options) {
if ( options === void 0 ) options = {};
var filter = createFilter(options.include, options.exclude);
var delimiters = options.delimiters;
var functionValues = mapToFunctions(getReplacements(options));
var keys = Object.keys(functionValues)
.sort(longest)
.map(escape);
var pattern = delimiters
? new RegExp(((escape(delimiters[0])) + "(" + (keys.join('|')) + ")" + (escape(delimiters[1]))), 'g')
: new RegExp(("\\b(" + (keys.join('|')) + ")\\b"), 'g');
return {
name: 'replace',
renderChunk: function renderChunk(code, chunk) {
var id = chunk.fileName;
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
},
transform: function transform(code, id) {
if (!keys.length) { return null; }
if (!filter(id)) { return null; }
return executeReplacement(code, id);
}
};
function executeReplacement(code, id) {
var magicString = new MagicString(code);
if (!codeHasReplacements(code, id, magicString)) {
return null;
}
var result = { code: magicString.toString() };
if (isSourceMapEnabled()) {
result.map = magicString.generateMap({ hires: true });
}
return result;
}
function codeHasReplacements(code, id, magicString) {
var result = false;
var match;
// eslint-disable-next-line no-cond-assign
while ((match = pattern.exec(code))) {
result = true;
var start = match.index;
var end = start + match[0].length;
var replacement = String(functionValues[match[1]](id));
magicString.overwrite(start, end, replacement);
}
return result;
}
function isSourceMapEnabled() {
return options.sourceMap !== false && options.sourcemap !== false;
}
}
export default replace;

35
node_modules/@rollup/plugin-replace/index.d.ts generated vendored Executable file
View File

@ -0,0 +1,35 @@
import { Plugin } from 'rollup';
type Replacement = string | ((id: string) => string);
export interface RollupReplaceOptions {
/**
* A minimatch pattern, or array of patterns, of files that should be
* processed by this plugin (if omitted, all files are included by default)
*/
include?: string | RegExp | ReadonlyArray<string | RegExp> | null;
/**
* Files that should be excluded, if `include` is otherwise too permissive.
*/
exclude?: string | RegExp | ReadonlyArray<string | RegExp> | null;
/**
* To replace every occurrence of `<@foo@>` instead of every occurrence
* of `foo`, supply delimiters
*/
delimiters?: [string, string];
/**
* You can separate values to replace from other options.
*/
values?: { [str: string]: Replacement };
/**
* All other options are treated as `string: replacement` replacers,
* or `string: (id) => replacement` functions.
*/
[str: string]: Replacement | RollupReplaceOptions['include'] | RollupReplaceOptions['values'];
}
/**
* Replace strings in files while bundling them.
*/
export default function replace(options?: RollupReplaceOptions): Plugin;

104
node_modules/@rollup/plugin-replace/package.json generated vendored Normal file
View File

@ -0,0 +1,104 @@
{
"_from": "@rollup/plugin-replace",
"_id": "@rollup/plugin-replace@2.3.1",
"_inBundle": false,
"_integrity": "sha512-qDcXj2VOa5+j0iudjb+LiwZHvBRRgWbHPhRmo1qde2KItTjuxDVQO21rp9/jOlzKR5YO0EsgRQoyox7fnL7y/A==",
"_location": "/@rollup/plugin-replace",
"_phantomChildren": {},
"_requested": {
"type": "tag",
"registry": true,
"raw": "@rollup/plugin-replace",
"name": "@rollup/plugin-replace",
"escapedName": "@rollup%2fplugin-replace",
"scope": "@rollup",
"rawSpec": "",
"saveSpec": null,
"fetchSpec": "latest"
},
"_requiredBy": [
"#DEV:/",
"#USER"
],
"_resolved": "https://registry.npmjs.org/@rollup/plugin-replace/-/plugin-replace-2.3.1.tgz",
"_shasum": "16fb0563628f9e6c6ef9e05d48d3608916d466f5",
"_spec": "@rollup/plugin-replace",
"_where": "/home/juan/bigint-crypto-utils",
"author": {
"name": "Rich Harris",
"email": "richard.a.harris@gmail.com"
},
"ava": {
"files": [
"!**/fixtures/**",
"!**/helpers/**",
"!**/recipes/**",
"!**/types.ts"
]
},
"bugs": {
"url": "https://github.com/rollup/plugins/issues"
},
"bundleDependencies": false,
"dependencies": {
"@rollup/pluginutils": "^3.0.4",
"magic-string": "^0.25.5"
},
"deprecated": false,
"description": "Replace strings in files while bundling",
"devDependencies": {
"@rollup/plugin-buble": "^0.21.0",
"del-cli": "^3.0.0",
"locate-character": "^2.0.5",
"rollup": "^1.27.14",
"source-map": "^0.7.3",
"typescript": "^3.7.4"
},
"files": [
"dist",
"index.d.ts",
"src",
"README.md"
],
"homepage": "https://github.com/rollup/plugins/tree/master/packages/replace#readme",
"keywords": [
"rollup",
"plugin",
"replace",
"es2015",
"npm",
"modules"
],
"license": "MIT",
"main": "dist/rollup-plugin-replace.cjs.js",
"module": "dist/rollup-plugin-replace.es.js",
"name": "@rollup/plugin-replace",
"peerDependencies": {
"rollup": "^1.20.0"
},
"publishConfig": {
"access": "public"
},
"repository": {
"type": "git",
"url": "git+https://github.com/rollup/plugins.git"
},
"scripts": {
"build": "rollup -c",
"ci:coverage": "nyc pnpm run test && nyc report --reporter=text-lcov > coverage.lcov",
"ci:lint": "pnpm run build && pnpm run lint",
"ci:lint:commits": "commitlint --from=${CIRCLE_BRANCH} --to=${CIRCLE_SHA1}",
"ci:test": "pnpm run test -- --verbose && pnpm run test:ts",
"lint": "pnpm run lint:js && pnpm run lint:docs && pnpm run lint:package",
"lint:docs": "prettier --single-quote --write README.md",
"lint:js": "eslint --fix --cache src test",
"lint:package": "prettier --write package.json --plugin=prettier-plugin-package",
"prebuild": "del-cli dist",
"prepare": "pnpm run build",
"prepublishOnly": "pnpm run lint && pnpm run test",
"pretest": "pnpm run build",
"test": "ava",
"test:ts": "tsc index.d.ts test/types.ts --noEmit"
},
"version": "2.3.1"
}

Some files were not shown because too many files have changed in this diff Show More